-
Notifications
You must be signed in to change notification settings - Fork 0
/
MaximumProductSubarray.java
62 lines (51 loc) · 1.13 KB
/
MaximumProductSubarray.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package ProjectFiles;
public class MaximumProductSubarray {
public static void main(String[] args) {
System.out.println(maxProduct(new int[]{-2,7,8}));
}
public static int maxProduct(int[] nums) {
if(nums == null)
return 0;
int result = nums[0], productSoFar = result;
boolean isOddNegatives= false;
int second = Integer.MIN_VALUE;
if(result < 0){
isOddNegatives = true;
second = result;
}
for(int i = 1; i < nums.length ; i++){
int cur = nums[i];
if(cur == 0){
if(productSoFar < 0)
result = 0;
if(productSoFar > result )
result = productSoFar;
if(second > result )
result = second;
}
else if(cur < 0 ){
if(!isOddNegatives){
if(productSoFar > result )
result = productSoFar;
isOddNegatives = true;
second = 1;
}
else{
isOddNegatives = false;
if(second > result )
result = second;
second = -1;
}
}
productSoFar *= cur;
if(isOddNegatives && cur >0){
second *= cur;
}
}
if(productSoFar > result)
result = productSoFar;
if(second > result && second > 0 )
result = second;
return result;
}
}