FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/java/628_Maximum_Product_of_Three_Numbers.java at master · jakehoare/leetcode · GitHub
jakehoare
/
leetcode
Public
Notifications
You must be signed in to change notification settings
Fork
30
Star
51
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode
/
java
/
628_Maximum_Product_of_Three_Numbers.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
43 lines (37 loc) · 1.19 KB
Breadcrumbs
leetcode
/
java
/
628_Maximum_Product_of_Three_Numbers.java
Copy path
File metadata and controls
43 lines (37 loc) · 1.19 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
https://leetcode.com/problems/maximum-product-of-three-numbers/
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Solution can only be the product of the 3 largest numbers, or the largest and the 2 smallest.
Iterate over array, updating the 3 largest and 2 smallest numbers seen.
Alternatively, sort the array.
Time - O(n)
Space - O(1)
*/
class
Solution
{
public
int
maximumProduct
(
int
[]
nums
) {
int
max1
=
Integer
.
MIN_VALUE
;
int
max2
=
Integer
.
MIN_VALUE
;
int
max3
=
Integer
.
MIN_VALUE
;
int
min1
=
Integer
.
MAX_VALUE
;
int
min2
=
Integer
.
MAX_VALUE
;
for
(
int
num
:
nums
) {
if
(
num
>
max1
) {
max3
=
max2
;
max2
=
max1
;
max1
=
num
;
}
else
if
(
num
>
max2
) {
max3
=
max2
;
max2
=
num
;
}
else
if
(
num
>
max3
) {
max3
=
num
;
}
if
(
num
<
min1
) {
min2
=
min1
;
min1
=
num
;
}
else
if
(
num
<
min2
) {
min2
=
num
;
}
}
return
Math
.
max
(
max1
*
max2
*
max3
,
max1
*
min1
*
min2
);
}
}
Back
|
FazBrowse Home
|
New Git URL