Skip to content

Commit a55ecfb

Browse files
author
Tushar Roy
committed
python code for max product subarray
1 parent 9edf31d commit a55ecfb

2 files changed

Lines changed: 49 additions & 19 deletions

File tree

python/array/maxproductsubarray.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# http://www.geeksforgeeks.org/maximum-product-subarray/
2+
3+
def max_product(input):
4+
max_ending = 1
5+
min_ending = 1
6+
max_so_far = 1
7+
for i in input:
8+
if i > 0:
9+
max_ending = max_ending * i
10+
min_ending = min(min_ending*i, 1)
11+
elif i == 0:
12+
max_ending = 1
13+
min_ending = 1
14+
else:
15+
t = max_ending
16+
max_ending = max(min_ending*i, 1)
17+
min_ending = t * i
18+
if max_so_far < max_ending:
19+
max_so_far = max_ending
20+
return max_so_far
21+
22+
if __name__ == '__main__':
23+
input = [-6,-3,8,-9,-1,-1,3,6,9,0,3,-1]
24+
print(max_product(input))

src/com/interview/array/MaxProductSubarray.java

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,40 @@
11
package com.interview.array;
22

33
/**
4+
* Date 12/31/2015
5+
* @author Tushar Roy
6+
*
7+
* Given an array of postive and negative numbers find max product subarray.
8+
*
9+
* Time complexity is O(n)
10+
* Space complexity is O(1)
11+
*
412
* http://www.geeksforgeeks.org/maximum-product-subarray/
513
*/
614
public class MaxProductSubarray {
715

816
public int maxProduct(int input[]){
9-
int max = -1;
10-
int maxNeg = 1;
17+
int maxEnding = 1;
18+
int minEnding = 1;
1119
int maxSoFar = 1;
12-
for(int i =0; i < input.length; i++){
13-
if(input[i] == 0){
14-
maxNeg = 1;
15-
maxSoFar = 1;
16-
continue;
20+
for (int i = 0; i < input.length; i++) {
21+
if (input[i] > 0) {
22+
maxEnding = maxEnding*input[i];
23+
minEnding = Math.min(minEnding*input[i], 1);
24+
} else if (input[i] == 0) {
25+
maxEnding = 1;
26+
minEnding = 1;
27+
} else {
28+
int t = maxEnding;
29+
maxEnding = Math.max(minEnding*input[i], 1);
30+
minEnding = t * input[i];
1731
}
18-
if(input[i] < 0){
19-
maxSoFar = 1;
20-
}else{
21-
maxSoFar = maxSoFar * input[i];
22-
}
23-
maxNeg = maxNeg*input[i];
24-
if(max < maxNeg){
25-
max = maxNeg;
26-
}
27-
if(max < maxSoFar){
28-
max = maxSoFar;
32+
33+
if (maxSoFar < maxEnding) {
34+
maxSoFar = maxEnding;
2935
}
3036
}
31-
return max;
37+
return maxSoFar;
3238
}
3339

3440
public static void main(String args[]){

0 commit comments

Comments
 (0)