leetcode 152. Maximum Product Subarray
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[i][0]表示最小值,dp[i][1]表示最大值。
class Solution {
public:
int maxProduct(vector<int>& nums) {
int n = nums.size();
vector<vector<int> > dp(n, vector<int>(2));
int ans = INT_MIN;
if (n == 1) return nums[0];
for (int i = 0; i < nums.size(); ++i) {
if (i == 0) {
dp[i][1] = nums[i];
dp[i][0] = nums[i];
} else {
if (nums[i] > 0) {
dp[i][1] = max(dp[i-1][1]*nums[i],nums[i]);
dp[i][0] = min(dp[i-1][0]*nums[i],nums[i]);
}
else {
dp[i][1] = max(dp[i-1][0]*nums[i], nums[i]);
dp[i][0] = min(dp[i-1][1]*nums[i], nums[i]);
}
}
ans = max(max(dp[i][0],dp[i][1]), ans);
}
return ans;
}
};
这个代码还可以优化,比如不用数组,同时也不用判断nums[i]是大于0还是小于0
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: