-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximum_product_subarray.py
More file actions
35 lines (25 loc) · 1.08 KB
/
Copy pathmaximum_product_subarray.py
File metadata and controls
35 lines (25 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from typing import List
class Solution:
"""LeetCode #152 - Maximum Product Subarray (Medium)
https://leetcode.com/problems/maximum-product-subarray/
Largest product of a contiguous subarray.
"""
def maxProduct(self, nums: List[int]) -> int:
"""Kadane, but carrying two running values instead of one.
Sums only ever get worse when a prefix is negative, so Kadane drops it.
Products do not: a very negative running product becomes the maximum the
moment another negative arrives. So the minimum has to be carried too,
and a negative number swaps their roles.
Zeros reset both, which falls out of taking max/min against `num` itself
rather than special-casing them.
Time: O(n)
Space: O(1)
"""
best = high = low = nums[0]
for num in nums[1:]:
if num < 0:
high, low = low, high # a negative turns the best into the worst
high = max(num, high * num)
low = min(num, low * num)
best = max(best, high)
return best