Maximum Product Subarray
Medium dynamic-programming · arrays
Description
Constraints
1 <= n <= 20000
Examples
Input: nums = [2,3,-2,4]
Output: 6
Hints (1)
- Track both the maximum and minimum product ending here, because a negative can flip.
Solutions
Track max and min products. · Time O(n) · Space O(1)
func maxProduct(nums []int) int {
best, mx, mn := nums[0], nums[0], nums[0]
for i := 1; i < len(nums); i++ {
n := nums[i]
a, b := mx*n, mn*n
hi, lo := n, n
if a > hi {
hi = a
}
if b > hi {
hi = b
}
if a < lo {
lo = a
}
if b < lo {
lo = b
}
mx, mn = hi, lo
if mx > best {
best = mx
}
}
return best
}
Track max and min products. · Time O(n) · Space O(1)
function maxProduct(nums) {
let best = nums[0], max = nums[0], min = nums[0];
for (let i = 1; i < nums.length; i++) {
const n = nums[i];
const candidates = [n, max * n, min * n];
max = Math.max(...candidates);
min = Math.min(...candidates);
best = Math.max(best, max);
}
return best;
}
Track max and min products. · Time O(n) · Space O(1)
function maxProduct($nums) {
$best = $nums[0]; $max = $nums[0]; $min = $nums[0];
for ($i = 1; $i < count($nums); $i++) {
$n = $nums[$i];
$candidates = [$n, $max * $n, $min * $n];
$max = max($candidates); $min = min($candidates);
$best = max($best, $max);
}
return $best;
}
Track max and min products. · Time O(n) · Space O(1)
def maxProduct(nums):
best = mx = mn = nums[0]
for n in nums[1:]:
candidates = (n, mx * n, mn * n)
mx = max(candidates)
mn = min(candidates)
best = max(best, mx)
return best
Track max and min products. · Time O(n) · Space O(1)
function maxProduct(nums: number[]): number {
let best = nums[0], max = nums[0], min = nums[0];
for (let i = 1; i < nums.length; i++) {
const n = nums[i];
const candidates = [n, max * n, min * n];
max = Math.max(...candidates);
min = Math.min(...candidates);
best = Math.max(best, max);
}
return best;
}
Create a free account to submit solutions, track progress and save problems.
Create account