题目描述
Given an integer array nums
, find a contiguous non-empty subarray within the array that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6.
Example 2:
Input: nums = [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
Constraints:
1 <= nums.length <= 2 * 104
-10 <= nums[i] <= 10
- The product of any prefix or suffix of
nums
is guaranteed to fit in a 32-bit integer.
解题思路
【C++】
class Solution {
public:
int maxProduct(vector<int>& nums) {
if (nums.size() == 0) {return 0;}
vector<int> dpMax;
vector<int> dpMin;
dpMax.push_back(nums[0]);
dpMin.push_back(nums[0]);
int res = nums[0];
for (int i=1; i<nums.size(); i++) {
int tmpMax = dpMax[i-1] * nums[i], tmpMin = dpMin[i-1] * nums[i];
dpMax.push_back(max(max(tmpMax, tmpMin), nums[i]));
dpMin.push_back(min(min(tmpMax, tmpMin), nums[i]));
res = max(res, dpMax[i]);
}
return res;
}
};
【Java】
class Solution {
public int maxProduct(int[] nums) {
int[] dpMax = new int[nums.length];
int[] dpMin = new int[nums.length];
dpMax[0] = nums[0];
dpMin[0] = nums[0];
int res = nums[0];
for(int i=1; i<nums.length; i++) {
int tmpMax = dpMax[i-1] * nums[i], tmpMin = dpMin[i-1] * nums[i];
dpMax[i] = Math.max(Math.max(tmpMax, tmpMin),nums[i]);
dpMin[i] = Math.min(Math.min(tmpMax, tmpMin),nums[i]);
res = Math.max(dpMax[i], res);
}
return res;
}
}