Skip to content

Commit ccdb995

Browse files
committed
changed max_product_subarray program from ruby to python
1 parent 7cde6ce commit ccdb995

File tree

2 files changed

+34
-25
lines changed

2 files changed

+34
-25
lines changed

dp/max_product_subarray.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,37 @@ def max_product(nums):
1919
lmax = max(max(t1, t2), nums[i])
2020
lmin = min(min(t1, t2), nums[i])
2121
gmax = max(gmax, lmax)
22+
23+
24+
'''
25+
Another approach that would print max product and the subarray
26+
27+
Example:
28+
subarray_with_max_product([2,3,6,-1,-1,9,5])
29+
max_product_so_far: 45, [9, 5]
30+
31+
subarray_with_max_product([2,3,6,-1,-1,4,5])
32+
max_product_so_far: 36, [2, 3, 6]
33+
34+
subarray_with_max_product([-2,-3,6,-1,-9,-5])
35+
max_product_so_far: 6, [6]
36+
'''
37+
38+
def subarray_with_max_product(arr):
39+
l = len(arr)
40+
product_so_far = max_product_end = 1
41+
max_start_i = 0
42+
so_far_start_i = so_far_end_i = 0
43+
44+
for i in range(l):
45+
max_product_end *= arr[i]
46+
47+
if max_product_end < 0:
48+
max_product_end = 1
49+
max_start_i = i + 1
50+
51+
if product_so_far < max_product_end:
52+
product_so_far = max_product_end
53+
so_far_end_i = i
54+
so_far_start_i = max_start_i
55+
print "max_product_so_far: %s, %s"%(product_so_far, arr[so_far_start_i:so_far_end_i+1])

dp/max_product_subarray_another_approach.rb

Lines changed: 0 additions & 25 deletions
This file was deleted.

0 commit comments

Comments
 (0)