
Problem
Solution
Submissions
Maximum Product Subarray
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to find the maximum product of a contiguous subarray within a one-dimensional array of numbers. The array contains both positive and negative integers. You need to find the subarray with the largest product.
Example 1
- Input: nums = [2, 3, -2, 4]
- Output: 6
- Explanation:
- All possible subarrays are [2], [3], [-2], [4], [2,3], [3,-2], [-2,4], [2,3,-2], [3,-2,4], [2,3,-2,4].
- Their products are 2, 3, -2, 4, 6, -6, -8, -12, -24, -48.
- The subarray [2,3] has the maximum product of 6.
- Therefore, the maximum product is 6.
- All possible subarrays are [2], [3], [-2], [4], [2,3], [3,-2], [-2,4], [2,3,-2], [3,-2,4], [2,3,-2,4].
Example 2
- Input: nums = [-2, 0, -1]
- Output: 0
- Explanation:
- All possible subarrays include [0] which has product 0.
- Other subarrays like [-2], [-1], [-2,0], [0,-1], [-2,0,-1] have products -2, -1, 0, 0, 0.
- The maximum product among all is 0.
- Therefore, the result is 0.
- All possible subarrays include [0] which has product 0.
Constraints
- 1 ≤ nums.length ≤ 2 × 10^4
- -10 ≤ nums[i] ≤ 10
- The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Keep track of both maximum and minimum product ending at each position
- For each element, calculate new max and min considering current element
- Handle negative numbers by swapping max and min when current number is negative
- Update the global maximum product at each step
- Consider the case where current element itself might be the maximum product