Skip to content

Commit 87eb373

Browse files
committed
handled case when list has all negitive numbers or includes 0
1 parent 1e272e1 commit 87eb373

1 file changed

Lines changed: 22 additions & 14 deletions

File tree

dp/max_product_subarray.py

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,15 @@ def max_product(nums):
2424
'''
2525
Another approach that would print max product and the subarray
2626
27-
Example:
27+
Examples:
2828
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]
29+
#=> max_product_so_far: 45, [-1, -1, 9, 5]
30+
subarray_with_max_product([-2,-3,6,0,-7,-5])
31+
#=> max_product_so_far: 36, [-2, -3, 6]
32+
subarray_with_max_product([-4,-3,-2,-1])
33+
#=> max_product_so_far: 24, [-4, -3, -2, -1]
34+
subarray_with_max_product([-3,0,1])
35+
#=> max_product_so_far: 1, [1]
3636
'''
3737

3838
def subarray_with_max_product(arr):
@@ -41,16 +41,24 @@ def subarray_with_max_product(arr):
4141
product_so_far = max_product_end = 1
4242
max_start_i = 0
4343
so_far_start_i = so_far_end_i = 0
44+
all_negitive_flag = True
4445

4546
for i in range(l):
4647
max_product_end *= arr[i]
47-
if max_product_end < 0:
48-
max_product_end = 1
49-
max_start_i = i + 1
48+
if arr[i] > 0: all_negitive_flag = False
49+
50+
if max_product_end <= 0:
51+
max_product_end = arr[i]
52+
max_start_i = i
5053

51-
if product_so_far < max_product_end:
54+
if product_so_far <= max_product_end:
5255
product_so_far = max_product_end
5356
so_far_end_i = i
5457
so_far_start_i = max_start_i
55-
print "max_product_so_far: %s, %s" % (product_so_far,\
56-
arr[so_far_start_i:so_far_end_i + 1])
58+
59+
if all_negitive_flag:
60+
print "max_product_so_far: %s, %s" % \
61+
(reduce(lambda x, y: x * y, arr), arr)
62+
else:
63+
print "max_product_so_far: %s, %s" % (product_so_far,\
64+
arr[so_far_start_i:so_far_end_i + 1])

0 commit comments

Comments
 (0)