首页 > 代码库 > [LeetCode] Maximum Product Subarray
[LeetCode] Maximum Product Subarray
题目描述:
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
.
解题方案:
转载地址:http://blog.csdn.net/sbitswc/article/details/39546719
最大值的产生:
- if A[i] > 0, MaxValue = http://www.mamicode.com/A[i] * MaxValue
- if A[i] < 0, MinValue = http://www.mamicode.com/A[i] * MinValue
- A[i]
下面是该题代码:
1 class Solution { 2 public: 3 int maxProduct(int A[], int n) { 4 if (n == 0) {return 0;} 5 if (n == 1) {return A[0];} 6 7 int result = A[0]; 8 int CurMin = A[0]; 9 int CurMax = A[0];10 11 for (int i = 1; i < n; ++i) {12 int temp = CurMin * A[i];13 CurMin = min(A[i], min(temp, CurMax * A[i]));14 CurMax = max(A[i], max(temp, CurMax * A[i]));15 result = max(result, CurMax);16 }17 18 return result;19 }20 };
[LeetCode] Maximum Product Subarray
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。