152. Maximum Product Subarray
Posted 蓝色地中海
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
152. Maximum Product Subarray(js)
leetcode 152. Maximum Product Subarray
刷题152. Maximum Product Subarray