Find the contiguous subarray within an array which has the largest product.
Problem Statement
Examples
Input: nums = [2, 3, -2, 4]
Output: 6
Explanation: [2, 3] has the largest product 6.
Input: nums = [-2, 0, -1]
Output: 0
Explanation: Combining the input according to Maximum Product Subarray in an Array logic yields 0.
Input: nums = [-2, 3, -4]
Output: 24
Explanation: Combining the input according to Maximum Product Subarray in an Array logic yields 24.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
A negative number multiplied by the minimum (most negative) product becomes a large positive number. Therefore, maintaining both the current maximum and minimum products ending at position i allows O(N) time and O(1) space.
Step-by-Step Approach
- Initialize
max = nums[0], min = nums[0], result = nums[0]. - Iterate
ifrom1tonums.length - 1. - If
nums[i] < 0, swapmaxandmin. - Update
max = Math.max(nums[i], max * nums[i]). - Update
min = Math.min(nums[i], min * nums[i]). - Update
result = Math.max(result, max). - Return
result.
Optimal Implementation (JavaScript)
function maxProduct(nums) {
let max = nums[0], min = nums[0], result = nums[0];
for (let i = 1; i < nums.length; i++) {
const num = nums[i];
if (num < 0) {
const temp = max;
max = min;
min = temp;
}
max = Math.max(num, max * num);
min = Math.min(num, min * num);
result = Math.max(result, max);
}
return result;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Array with zeroes: resets current product.
- All negative numbers.
- Single element array.