π Introduction
Given an integer array nums
, find a contiguous non-empty subarray within the array that has the largest product, and return the product.
The problem requires handling negative numbers and zeros, which can disrupt the product and reset subarrays. A subarray must be contiguous, and the result must be the largest product among all possible subarrays.
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.
π‘ Approach & Key Insights
To solve this problem, we evaluate various approaches:
- Brute-force: Try all subarrays and compute their products.
- Optimized: Observe properties of negative numbers and zeros.
- Best: Use a modified version of Kadaneβs algorithm that tracks both max and min products to handle sign flips.
Key observations:
- Positive product β Keep multiplying.
- Negative product β Might become maximum when multiplied with another negative.
- Zeros β Break the subarray and reset.
π οΈ Breakdown of Approaches
1οΈβ£ Brute Force / Naive Approach
-
Explanation:
Generate all possible subarrays using two nested loops. For each subarray, calculate the product of its elements. Keep track of the maximum product seen so far. -
Time Complexity:
O(N^2)
β N starting points and N subarray lengths -
Space Complexity:
O(1)
β No extra space used beyond variables -
Example/Dry Run:
Example input: [2, 3, -2, 4]Subarrays:[2] β 2[2, 3] β 6[2, 3, -2] β -12[3, -2] β -6[-2, 4] β -8Max = 6Optimized Approach
Explanation:Based on the number of negative elements:
If all positives β result is the product of the entire array.
If even number of negatives β product of entire array is positive.
If odd number of negatives β remove one negative (either from start or end) to make the product positive.
Handle 0s by splitting the array into subarrays and applying the above logic on each.
Algorithm:prefix_product = 1suffix_product = 1max_product = nums[0]
for i in range(len(nums)): prefix_product *= nums[i] suffix_product *= nums[-1-i] max_product = max(max_product, prefix_product, suffix_product) if nums[i] == 0: prefix_product = 1 if nums[-1-i] == 0: suffix_product = 1Time Complexity: O(N) β Single pass
Space Complexity: O(1) β Only scalar variables used
Example/Dry Run:Input: [-2, 3, 4, -1, 0, -2, 3, 1, 4, 0, 4, 6, -1, 4]Break on zeros β [[-2,3,4,-1], [-2,3,1,4], [4,6,-1,4]]Answer = max of all segment max products
Best / Final Optimized Approach (Kadane-style)
Explanation:Track the maximum and minimum product ending at the current index. Negative numbers can flip max to min and vice versa. This ensures handling of alternating signs.
Algorithm:prod1 = prod2 = result = nums[0]
for i in range(1, len(nums)): current = nums[i] temp = max(current, current * prod1, current * prod2) prod2 = min(current, current * prod1, current * prod2) prod1 = temp result = max(result, prod1)Time Complexity: O(N) β Single loop
Space Complexity: O(1) β Constant number of variables
Example/Dry Run:Input: [1, 2, -3, 0, -4, -5]
Step 1: prod1 = prod2 = result = 1i = 1: nums[i] = 2 β temp = max(2, 2*1, 2*1) = 2 prod1 = 2, prod2 = 2, result = 2i = 2: nums[i] = -3 β temp = max(-3, -6, -6) = -3 prod1 = -3, prod2 = -6, result = 2i = 3: nums[i] = 0 β temp = 0 β reseti = 4: nums[i] = -4 β ...Final result: 20
---
## π Complexity Analysis
| Approach | Time Complexity | Space Complexity || ------------- | --------------- | ---------------- || Brute Force | O(NΒ²) | O(1) || Optimized | O(N) | O(1) || Best Approach | O(N) | O(1) |
---
## π Optimization Ideas
- Use rolling variables instead of arrays to track max/min products.- Restart subarray product after encountering 0 to ensure correct segmentation.- Can further optimize by using prefix/suffix scans with early exits.
---
## π Example Walkthroughs & Dry Runs
plaintextExample:Input: [2, 3, -2, 4]Process:β 2 β max = 2β 2Γ3 = 6 β max = 6β 6Γ(-2) = -12 β becomes minβ restart with 4 β max = 6Output: 6
Another:Input: [1, 2, -3, 0, -4, -5]β Subarray after 0 = [-4, -5] β product = 20Output: 20
---
## π Additional Resources
- [Kadaneβs Algorithm for Maximum Sum](https://en.wikipedia.org/wiki/Maximum_subarray_problem)
---
Author: Abdul WahabDate: 19/07/2025