Skip to content

Commit e7b2d56

Browse files
author
applewjg
committed
Maximum Product subarray
Change-Id: I90e90631a47fc030d5e1996f1c2bd611e0d92bc1
1 parent ffcfc40 commit e7b2d56

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

MaximumProductSubarray.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Oct 06, 2014
4+
Problem: Maximum Product Subarray
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/maximum-product-subarray/
7+
Notes:
8+
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
9+
10+
For example, given the array [2,3,-2,4],
11+
the contiguous subarray [2,3] has the largest product = 6.
12+
*/
13+
14+
public class Solution {
15+
public int maxProduct(int[] A) {
16+
if (A.length <= 0) {
17+
return 0;
18+
}
19+
int maxVal = A[0], minVal = A[0], res = A[0];
20+
for (int i = 1; i < A.length; ++i) {
21+
int tmpVal = maxVal;
22+
maxVal = Math.max(Math.max(maxVal * A[i], minVal * A[i]), A[i]);
23+
minVal = Math.min(Math.min(tmpVal * A[i], minVal * A[i]), A[i]);
24+
res = Math.max(res, maxVal);
25+
}
26+
return res;
27+
}
28+
}

0 commit comments

Comments
 (0)