Skip to content

Commit db18001

Browse files
committed
add maximum product subarray
1 parent c867c71 commit db18001

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

maximum_product_subarray.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import unittest
2+
3+
4+
class Solution:
5+
# @param A, a list of integers
6+
# @return an integer
7+
def maxProduct(self, A):
8+
# subproblem is maxProduct(A[n-1])
9+
# looks like optimal substructrure, dp should be applicable
10+
#
11+
# let's use:
12+
# m: positive product for A[x:i], initial with 0
13+
# n: negative product for A[x:i], initial with 0
14+
#
15+
# for example [2,3,-2,4]
16+
# i 2 3 -2 4
17+
# m 2 6 0 4
18+
# n 0 0 -12 -48
19+
# best 2 6 6 6
20+
if not A:
21+
raise ValueError
22+
if len(A) == 1:
23+
return A[0]
24+
25+
m, n, best = 0, 0, float('-inf')
26+
for i in A:
27+
if i >= 0:
28+
m, n = max(m * i, i), n * i
29+
else:
30+
m, n = n * i, min(m * i, i)
31+
best = max(m, best)
32+
return best
33+
34+
35+
36+
class Test(unittest.TestCase):
37+
38+
def test(self):
39+
s = Solution()
40+
self.assertEqual(s.maxProduct([-2,0,-1]), 0)
41+
self.assertEqual(s.maxProduct([-4,-3,-2]), 12)
42+
self.assertEqual(s.maxProduct([2,3,-2,4]), 6)
43+
self.assertEqual(s.maxProduct([-2]), -2)
44+
self.assertEqual(s.maxProduct([0.1, 0.1, 2]), 2)
45+
self.assertEqual(s.maxProduct([-2, 2, -2]), 8)
46+
self.assertEqual(s.maxProduct([0, -2, 4]), 4)
47+
self.assertEqual(s.maxProduct([0, -2, -2, 4]), 16)
48+
self.assertEqual(s.maxProduct([1, -2, 2, 2, 4]), 16)
49+
50+
51+
if __name__ == '__main__':
52+
unittest.main()

0 commit comments

Comments
 (0)