🔗 Problem Link: Maximum Product Subarray
Given an integer array nums
, find a contiguous subarray 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.
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
Constraints:
1 <= nums.length <= 2 * 104
-10 <= nums[i] <= 10
The product of any subarray of nums is guaranteed to fit in a 32-bit integer.
A naive approach would be to iterate through all possible subarrays and compute their product.
- Start at each index and multiply it with the next elements, keeping track of the maximum product.
- This results in a time complexity of O(n²), which is inefficient for large inputs.
To improve efficiency, we use a dynamic tracking method to handle both positive and negative numbers effectively.
-
Tracking Maximum & Minimum Products
- Since multiplying a negative number with a small (negative) product can make it large, we track both the maximum (
curmax
) and minimum (curmin
) products at each step. - For each number, we calculate:
curmax = max(n * curmax, n * curmin, n) curmin = min(temp, n * curmin, n)
- This ensures we correctly handle cases where negatives flip signs.
- Since multiplying a negative number with a small (negative) product can make it large, we track both the maximum (
-
Handling Zeroes
- If
0
is encountered, multiplying further would result in zero. - To prevent
curmax
andcurmin
from being permanently affected, we reset them to1
whenever a0
appears.
- If
Since we traverse the array only once, the solution runs in linear time, making it highly efficient.
Step | n |
curmax |
curmin |
res |
---|---|---|---|---|
1st Iteration | 2 | 2 | 2 | 2 |
2nd Iteration | 3 | 6 | 3 | 6 |
3rd Iteration | -2 | -2 | -12 | 6 |
4th Iteration | 4 | 4 | -48 | 6 |
Final Output: 6
This approach ensures we efficiently find the maximum product subarray in just O(n) time complexity. 🚀