题目来源:https://leetcode.com/problems/maximum-product-subarray/
问题描述
152. Maximum Product Subarray
Medium
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
------------------------------------------------------------
题意
求数列的连续子列的最大积
------------------------------------------------------------
思路
动态规划。
仿照经典动态规划问题最大子列和的解法,但是由于乘法正负会变号,因此维护两个dp数组pos和neg,pos[i]和neg[i]分别表示以i结尾的子列的最大正乘积和最小负乘积。
------------------------------------------------------------
代码
class Solution {
public int maxProduct(int[] nums) {
int n = nums.length, i = 0;
if (n == 0) {
return 0;
} else if (n == 1) {
return nums[0];
}
int[] pos = new int[n];
int[] neg = new int[n];
if (nums[0] == 0) {
neg[0] = 0;
pos[0] = 0;
} else if (nums[0] < 0) {
neg[0] = nums[0];
pos[0] = 0;
} else {
neg[0] = 0;
pos[0] = nums[0];
}
for (i=1; i<n; ++i) {
if (nums[i] == 0) {
neg[i] = 0;
pos[i] = 0;
} else if (nums[i] < 0) {
neg[i] = pos[i-1] == 0? nums[i]: pos[i-1] * nums[i];
pos[i] = neg[i-1] == 0? 0: neg[i-1] * nums[i];
} else {
neg[i] = neg[i-1] == 0? 0: neg[i-1] * nums[i];
pos[i] = pos[i-1] == 0? nums[i]: pos[i-1] * nums[i];
}
}
int maxprod = 0;
for (int po: pos) {
maxprod = po>maxprod? po: maxprod;
}
return maxprod;
}
}