Algorithm Day89 - Maximum Product Subarray
π§© Problem Description
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product, and return the product.
π¬ Examples
Example 1
1 | Input: nums = [2,3,-2,4] |
Example 2
1 | Input: nums = [-2,0,-1] |
π‘ Intuition
Because the product of numbers is affected by the sign, a negative number can turn a small (negative) product into a large positive one, and vice versa. Therefore, at each position we need to track both the maximum and minimum product ending at that position.
Let maxF[i] be the maximum product ending at i, and minF[i] the minimum product ending at i. Then:
1 | maxF[i] = max(nums[i], nums[i] * maxF[i-1], nums[i] * minF[i-1]) |
We can optimize space by keeping only previous max and min values.
π’ Java Code (DP, O(1) space)
1 | class Solution { |
β± Complexity Analysis
- Time: O(n) β single pass through the array.
- Space: O(1) β constant extra space.
βοΈ Summary
- Track both maximum and minimum products at each step because negative numbers can flip signs.
- Swap max/min when encountering a negative number before updating.
- Keep a running global maximum answer.
Related problems
lc-53β Maximum Subarray (Kadaneβs algorithm)lc-918β Maximum Sum Circular Subarray