-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode-152-Maximum-Product-Subarray.java
More file actions
69 lines (58 loc) · 2.09 KB
/
LeetCode-152-Maximum-Product-Subarray.java
File metadata and controls
69 lines (58 loc) · 2.09 KB
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
63
64
65
66
67
68
69
public class Solution {
// 1.
/*
https://leetcode.com/problems/maximum-product-subarray/discuss/48252/Sharing-my-solution%3A-O(1)-space-O(n)-running-time
https://leetcode.com/problems/maximum-product-subarray/discuss/48330/Simple-Java-code
*/
// public int maxProduct(int[] nums) {
// if (nums == null || nums.length == 0) return 0;
// int min = nums[0], max = nums[0], result = nums[0];
// for (int i = 1; i < nums.length; i++) {
// int temp = max;
// max = Math.max(Math.max(max * nums[i], min * nums[i]), nums[i]);
// min = Math.min(Math.min(temp * nums[i], min * nums[i]), nums[i]);
// result = Math.max(result, max);
// }
// return result;
// }
// 2.
/*
Inspired by: https://leetcode.com/problems/maximum-product-subarray/discuss/48230/Possibly-simplest-solution-with-O(n)-time-complexity
*/
// public int maxProduct(int[] nums) {
// if (nums == null || nums.length == 0) return 0;
// int min = nums[0], max = nums[0], result = nums[0];
// for (int i = 1; i < nums.length; i++) {
// if (nums[i] < 0) {
// int temp = max;
// max = min;
// min = temp;
// }
// max = Math.max(max * nums[i], nums[i]);
// min = Math.min(min * nums[i], nums[i]);
// result = Math.max(result, max);
// }
// return result;
// }
// 3.
/*
https://leetcode.com/problems/maximum-product-subarray/discuss/48404/Accepted-Java-solution
*/
public int maxProduct(int[] a) {
if (a == null || a.length == 0)
return 0;
int ans = a[0], min = ans, max = ans;
for (int i = 1; i < a.length; i++) {
if (a[i] >= 0) {
max = Math.max(a[i], max * a[i]);
min = Math.min(a[i], min * a[i]);
} else {
int tmp = max;
max = Math.max(a[i], min * a[i]);
min = Math.min(a[i], tmp * a[i]);
}
ans = Math.max(ans, max);
}
return ans;
}
}