本文主要是介绍152. Maximum Product Subarray dynamic programming,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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.
最大成绩可能是负数与负数的乘积或者正数与正数的乘积;
int maxProduct(vector<int>& nums) {if (nums.size() == 0)return 0;int posinum = nums[0];int neginum = nums[0];int sum = nums[0];for (int i = 1; i < nums.size(); i++){int tempposi = posinum;int tempnegi = neginum;posinum = max(nums[i], max(tempposi * nums[i], tempnegi * nums[i]));neginum = min(nums[i], min(tempposi * nums[i], tempnegi * nums[i]));sum = max(sum, posinum);}return sum;
}
这篇关于152. Maximum Product Subarray dynamic programming的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!