@@ -19,3 +19,37 @@ def max_product(nums):
19
19
lmax = max (max (t1 , t2 ), nums [i ])
20
20
lmin = min (min (t1 , t2 ), nums [i ])
21
21
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 ])
0 commit comments