首页 > 代码库 > 152. Maximum Product Subarray
152. Maximum Product Subarray
Problem statement:
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4]
,
the contiguous subarray [2,3]
has the largest product = 6
.
Solution:
It is similar with 53. Maximum Subarray. We should keep one more minimum product since the product of two negative number is a position number. The current max and min value should choose from three candidates, nums[i], cur_max * nums[i] and cur_min * nums[i].
Time complexity is O(n).
class Solution {public: int maxProduct(vector<int>& nums) { if(nums.empty()){ return 0; } int cur_max = 0; int cur_min = 0; int pre_max = nums[0]; int pre_min = nums[0]; int tot_max = nums[0]; for(int i = 1; i < nums.size(); i++){ cur_max = max(nums[i], max(pre_max * nums[i], pre_min * nums[i])); cur_min = min(nums[i], min(pre_max * nums[i], pre_min * nums[i])); pre_max = cur_max; pre_min = cur_min; tot_max = max(tot_max, cur_max); } return tot_max; }};
152. Maximum Product Subarray
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。