Skip to content

Commit 6209eb7

Browse files
authored
added kadane's algorithm directory with one problem's solution.
1 parent ac111ee commit 6209eb7

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
def max_product_subarray(nums):
2+
"""
3+
Returns the maximum product that can be obtained by multiplying a
4+
contiguous subarray of the given integer list `nums`.
5+
6+
Example:
7+
>>> max_product_subarray([2, 3, -2, 4])
8+
6
9+
>>> max_product_subarray([-2, 0, -1])
10+
0
11+
>>> max_product_subarray([2, 3, -2, 4, -1])
12+
48
13+
"""
14+
n = len(nums)
15+
16+
if n == 0:
17+
return 0
18+
19+
max_till_now = nums[0]
20+
min_till_now = nums[0]
21+
max_prod = nums[0]
22+
23+
for i in range(1, n):
24+
# update the maximum and minimum subarray products
25+
if nums[i] < 0:
26+
max_till_now, min_till_now = min_till_now, max_till_now
27+
max_till_now = max(nums[i], max_till_now * nums[i])
28+
min_till_now = min(nums[i], min_till_now * nums[i])
29+
30+
# update the maximum product found till now
31+
max_prod = max(max_prod, max_till_now)
32+
33+
return max_prod

0 commit comments

Comments
 (0)