刷了两个月的hihocoder之后再回来刷leetcode觉得leetcode简单多了,
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 sum = 6.
Example 2:
Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.大致想法是遍历整个数组,记录到每个元素时的以这个元素结尾的子数组最大值和最小值,M(i)表示第i个元素的最大值,m(i)表示第i个元素的最小值。当这个元素是负数的时候,以这个元素结尾的子数组的最大值就是M(i) = max(nums[i],m(i - 1) * nums[i]),m(i) = min(nums[i],M(i - 1) * nums[i])。这个元素大于0时,M(i) = max(nums[i],M(i - 1) * nums[i]),m(i) = min(nums[i],M(i - 1) * nums[i])。
int maxProduct(vector<int>& nums) {
int length = nums.size();
int max1 = nums[0],min1 = nums[0];
int ans = nums[0];
for(int i = 1;i < length;++i)
{
int temp1 = min1,temp2 = max1;
if(nums[i] > 0)
{
min1 = min(nums[i],min1 * nums[i]);
max1 = max(nums[i] * max1,nums[i]);
}
else
{
min1 = min(nums[i],max1 * nums[i]);
max1 = max(nums[i],temp1 * nums[i]);
}
ans = max(ans,max1);
}
return ans;
}
还有一道是求子数组和的最大值。
int maxSubArray(vector<int>& nums) {
int length = nums.size(),ret = nums[0],ans = nums[0];
for(int i = 1;i < length;++i)
{
if(ret <= 0)
ret = nums[i];
else
ret += nums[i];
ans = max(ans,ret);
}
return ans;
}