@@ -19,3 +19,46 @@ 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+ Examples:
28+ subarray_with_max_product([2,3,6,-1,-1,9,5])
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]
36+ '''
37+
38+ def subarray_with_max_product (arr ):
39+ ''' arr is list of positive/negative numbers '''
40+ l = len (arr )
41+ product_so_far = max_product_end = 1
42+ max_start_i = 0
43+ so_far_start_i = so_far_end_i = 0
44+ all_negative_flag = True
45+
46+ for i in range (l ):
47+ max_product_end *= arr [i ]
48+ if arr [i ] > 0 : all_negative_flag = False
49+
50+ if max_product_end <= 0 :
51+ max_product_end = arr [i ]
52+ max_start_i = i
53+
54+ if product_so_far <= max_product_end :
55+ product_so_far = max_product_end
56+ so_far_end_i = i
57+ so_far_start_i = max_start_i
58+
59+ if all_negative_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