forked from dipsdeepak11/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
152_Maximum_Product_Subarray.java
55 lines (47 loc) · 1.43 KB
/
152_Maximum_Product_Subarray.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
// 2D array DP (Memory Exceed)
class Solution {
public int maxProduct(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int len = nums.length;
long[][] f = new long[len][len];
long max = (long) Integer.MIN_VALUE;
for (int i = 0; i < len; i++) {
f[i][i] = (long) nums[i];
max = Math.max(max, f[i][i]);
for (int j = 0; j < i; j++) {
f[j][i] = f[j][i - 1] * (long) nums[i];
max = Math.max(max, f[j][i]);
}
}
if (max < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
if (max > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
return (int) max;
}
}
// o(n)
class Solution {
public int maxProduct(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int len = nums.length;
int max = nums[0];
int curMax = nums[0];
int curMin = nums[0];
for (int i = 1; i < len; i++) {
int cur = nums[i];
int nextMax = curMax * cur;
int nextMin = curMin * cur;
curMax = Math.max(cur, Math.max(nextMax, nextMin));
curMin = Math.min(cur, Math.min(nextMax, nextMin));
max = Math.max(curMax, max);
}
return max;
}
}