1,题目要求
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.
给定整数数组nums,找到具有最大乘积的数组(包含至少一个数字)内的连续子数组。
2,题目思路
对于这道题,题目是找到具有最大乘积的数组的连续子数组。
连续数字的乘积,有个关键问题:存在负值。
因此,我们需要对负数情况进行处理。
在这道题目上,我们使用两个变量currMax
和currMin
,分别用来记录从开始位置到当前位置i
的可以获得的最大乘积值和最小乘积值。
而每当我们判断到nums[i] < 0
,则可以得知的是:
- 负数因子使得大的数变小,小的值变大
因此,此时我们交换最大值和最小值。
之后,我们再对currMax
和currMin
进行更新:
currMax = max(nums[i], currMax*nums[i]);
currMin = min(nums[i], currMin*nums[i]);
即当前数字的最大乘积要么是自己本身,要么是前面的最大乘积乘以当前数字。
最小乘积同理。
然后,更新res = max(res, currMax)
3,代码实现
int x = []() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution {
public:
int maxProduct(vector<int>& nums) {
int res = nums[0];
int currMax = nums[0], currMin = nums[0];
for(int i = 1;i < nums.size();i++){
if(nums[i] < 0)
swap(currMax, currMin);
currMax = max(nums[i], currMax*nums[i]);
currMin = min(nums[i], currMin*nums[i]);
res = max(res, currMax);
}
return res;
}
};