152_Maximum Product Subarray

Level: medium

Tag: array, dynamic programming

Question

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1

Input: nums = [2,3,-2,4]
Output: 6

Example 2

Input: nums = [2,3,-2,4,-2]
Output: 96

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: O(n)O(n)

  • Space: O(1)O(1)

Solution

Last updated

Was this helpful?