forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxProduct.java
More file actions
27 lines (24 loc) · 742 Bytes
/
MaxProduct.java
File metadata and controls
27 lines (24 loc) · 742 Bytes
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
package dynamic;
public class MaxProduct {
public int maxProduct(int[] nums) {
int max = Integer.MIN_VALUE,imax = 1,imin = 1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] < 0){
int tmp = imax;
imax = imin;
imin = tmp;
}
imax = Math.max(imax*nums[i],nums[i]);
imin = Math.min(imin*nums[i],nums[i]);
max = Math.max(max,imax);
}
return max;
}
public static void main(String[] args) {
int[] nums = {2, 3, -2, 4};
int[] nums1 = {-2};
MaxProduct maxProduct = new MaxProduct();
int r = maxProduct.maxProduct(nums1);
System.out.println(r);
}
}