-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaxProduct.java
More file actions
32 lines (29 loc) · 930 Bytes
/
MaxProduct.java
File metadata and controls
32 lines (29 loc) · 930 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
28
29
30
31
32
package com.algorithm.dynamicprogramming;
public class MaxProduct {
/**
* #152
* https://leetcode-cn.com/problems/maximum-product-subarray/
*
* @param args
*/
public static void main(String[] args) {
int[] nums = new int[] { 0, 2 };
System.out.println(maxProduct(nums));
}
public static int maxProduct(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int n = nums.length;
int[] maxp = new int[n], minp = new int[n];
int res = nums[0];
maxp[0] = nums[0];
minp[0] = nums[0];
for (int i = 1; i < n; i++) {
maxp[i] = Math.max(Math.max(minp[i - 1] * nums[i], nums[i]), maxp[i - 1] * nums[i]);
minp[i] = Math.min(Math.min(minp[i - 1] * nums[i], nums[i]), maxp[i - 1] * nums[i]);
res = Math.max(maxp[i], res);
}
return res;
}
}