152_Maximum Product Subarray
Level: medium
Tag: array, dynamic programming
Question
Example 1
Example 2
Idea (dynamic programing)
Two steps to solve this problem:
Suppose we've solved the problem for nums[1 .. i - 1], how can we extend that to nums[1 .. i]? maxProduct(nums[1 .. i]) is either maxProduct(nums[1 .. i-1]) (which we call Max), or it is maximum product of a subvector that ends in position i (which we call curMax).
What's the maximum product of a subvector that ends in position i? Three possibilities:
just i itself
i * curMax, where curMax records the maximum with element 0, ..., i-1
i * curMin, where curMin records the minimum with element 0, ... , i-1. Because negative curMin may be the next curMax when i is negative.
Complexity
Time:
Space:
Solution
Last updated