Maximum Product Subarray
Maximum Product Subarray
Problem Statement
Given an integer array nums
, find a contiguous non-empty subarray within the array that has the largest product, and return the product. The test cases are generated so that the answer will fit in a 32-bit integer.
Example
Input: nums = [2,3,-2,4]
nums: [2, 3, -2, 4]
Output: 6
Output: 6
The subarray [2,3] has the largest product 6.
Solution
The key to this problem is to realize that the maximum product can be formed by either a positive number multiplied by a previous maximum product, or a negative number multiplied by a previous minimum product. Therefore, we need to keep track of both the maximum and minimum product ending at the current position.
Algorithm Steps
- Initialize `max_so_far`, `min_so_far`, and `result` to the first element of the array.
- Iterate through the array from the second element.
- For each element, the new `max_so_far` is the maximum of the element itself, the element multiplied by the previous `max_so_far`, and the element multiplied by the previous `min_so_far`.
- Similarly, the new `min_so_far` is the minimum of these three values.
- Update the overall `result` with the new `max_so_far`.
- Return `result`.
Maximum Product Subarray
Dynamic Programming Approach
Input: nums = [2, 3, -2, 4]
Output: 0
Ready to start the visualization
Nums
Max So Far
Min So Far