Skip to content

Commit 926d1cb

Browse files
committed
Create Maximum_Product_Subarray.cc
DP. In order to deal with the negatives, it needs to mark down the maximum(>0) and minimum result(<0) at the same time.
1 parent a731a39 commit 926d1cb

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

Maximum_Product_Subarray.cc

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public:
3+
int maxProduct(int A[], int n) {
4+
if (n <= 0) return 0;
5+
int iMaxProductEndByPrePos = A[0], iMaxProductEndByCurrentPos;
6+
int iMinProductEndByPrePos = A[0], iMinProductEndByCurrentPos;
7+
int ret = A[0];
8+
for (int i = 1; i < n; i++) {
9+
iMaxProductEndByCurrentPos = max(max(iMaxProductEndByPrePos * A[i], iMinProductEndByPrePos * A[i]), A[i]);
10+
iMinProductEndByCurrentPos = min(min(iMaxProductEndByPrePos * A[i], iMinProductEndByPrePos * A[i]), A[i]);
11+
ret = max(ret, iMaxProductEndByCurrentPos);
12+
iMaxProductEndByPrePos = iMaxProductEndByCurrentPos;
13+
iMinProductEndByPrePos = iMinProductEndByCurrentPos;
14+
}
15+
return ret;
16+
}
17+
};

0 commit comments

Comments
 (0)