-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMaxProductOfThreeNumbers.java
64 lines (43 loc) · 1.48 KB
/
MaxProductOfThreeNumbers.java
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
44
45
package array_and_matrix;
/**
* @Author: Wenhang Chen
* @Description:给定一个整型数组,在数组中找出由三个数组成的最大乘积,并输出这个乘积。 示例 1:
* <p>
* 输入: [1,2,3]
* 输出: 6
* 示例 2:
* <p>
* 输入: [1,2,3,4]
* 输出: 24
* 注意:
* <p>
* 给定的整型数组长度范围是[3,104],数组中所有的元素范围是[-1000, 1000]。
* 输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。
* @Date: Created in 15:20 6/26/2020
* @Modified by:
*/
public class MaxProductOfThreeNumbers {
public int maximumProduct(int[] nums) {
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;
for (int n : nums) {
if (n <= min1) {
min2 = min1;
min1 = n;
} else if (n <= min2) { // n lies between min1 and min2
min2 = n;
}
if (n >= max1) { // n is greater than max1, max2 and max3
max3 = max2;
max2 = max1;
max1 = n;
} else if (n >= max2) { // n lies betweeen max1 and max2
max3 = max2;
max2 = n;
} else if (n >= max3) { // n lies betwen max2 and max3
max3 = n;
}
}
return Math.max(min1 * min2 * max1, max1 * max2 * max3);
}
}