问题描述:
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[i] 进行比较。
mx[i] = max(max(prod1, prod2), nums[i]);
mn[i] = min(min(prod1, prod2), nums[i]);
代码:
class Solution { public: int maxProduct(vector<int>& nums) { if(nums.size() == 0) return 0; if(nums.size() == 1) return nums[0]; vector<int> mx(nums.size()); vector<int> mn(nums.size()); mx[0] = nums[0]; mn[0] = nums[0]; int ret = mx[0]; for(int i = 1; i < nums.size(); i++){ int prod1 = mx[i-1]*nums[i]; int prod2 = mn[i-1]*nums[i]; mx[i] = max(max(prod1, prod2), nums[i]); mn[i] = min(min(prod1, prod2), nums[i]); ret = max(mx[i], ret); } return ret; } };