Leetcode
Dynamic Programming
152 Maximum Product Subarray

1. Question

Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array[2,3,-2,4], the contiguous subarray[2,3]has the largest product =6.

2. Implementation

(1) DP
1
class Solution {
2
public int maxProduct(int[] nums) {
3
if (nums == null || nums.length == 0) {
4
return 0;
5
}
6
7
int n = nums.length;
8
int res = nums[0];
9
int max = nums[0];
10
int min = nums[0];
11
12
for (int i = 1; i < n; i++) {
13
if (nums[i] >= 0) {
14
max = Math.max(nums[i], max * nums[i]);
15
min = Math.min(nums[i], min * nums[i]);
16
}
17
else {
18
int temp = max;
19
max = Math.max(nums[i], min * nums[i]);
20
min = Math.min(nums[i], temp * nums[i]);
21
}
22
res = Math.max(res, max);
23
}
24
return res;
25
}
26
}
Copied!

3. Time & Space Complexity

DP: 时间复杂度O(n), 空间复杂度O(n)