
Problem
Solution
Submissions
Maximum Product of a Subarray
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.
Example 1
- Input: nums = [2, 3, -2, 4]
- Output: 6
- Explanation:
- Step 1: Consider all contiguous subarrays of nums [2, 3, -2, 4].
- Step 2: Calculate the product of elements in each subarray.
- Step 3: Subarray [2] has product 2.
- Step 4: Subarray [3] has product 3.
- Step 5: Subarray [-2] has product -2.
- Step 6: Subarray [4] has product 4.
- Step 7: Subarray [2, 3] has product 6.
- Step 8: Subarray [3, -2] has product -6.
- Step 9: Subarray [-2, 4] has product -8.
- Step 10: Subarray [2, 3, -2] has product -12.
- Step 11: Subarray [3, -2, 4] has product -24.
- Step 12: Subarray [2, 3, -2, 4] has product -48.
- Step 13: The maximum product is 6 from the subarray [2, 3].
Example 2
- Input: nums = [-2, 0, -1]
- Output: 0
- Explanation:
- Step 1: Consider all contiguous subarrays of nums [-2, 0, -1].
- Step 2: Calculate the product of elements in each subarray.
- Step 3: Subarray [-2] has product -2.
- Step 4: Subarray [0] has product 0.
- Step 5: Subarray [-1] has product -1.
- Step 6: Subarray [-2, 0] has product 0.
- Step 7: Subarray [0, -1] has product 0.
- Step 8: Subarray [-2, 0, -1] has product 0.
- Step 9: The maximum product is 0 from the subarrays containing 0.
Constraints
- 1 ≤ nums.length ≤ 2 × 10^4
- -10 ≤ nums[i] ≤ 10
- The product of any subarray will not exceed the range of a 32-bit signed 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
- Consider both maximum and minimum products at each position to handle negative numbers
- A negative number can turn the minimum product (which could be very negative) into a large positive product
- Reset your calculations when encountering zeros
- Keep track of the global maximum product seen so far
- Consider using dynamic programming to solve this problem efficiently