152. Maximum Product Subarray
Asked at 22Amazon53Bloomberg53Google51Microsoft43Meta41LinkedIn72tcs63Infosys50Delhivery100Adobe74Siemens65Morgan Stanley64HashedIn62Swiggy59DE Shaw58Qualcomm58ByteDance50Juspay47IBM44Walmart Labs43Goldman Sachs28TikTok26
Problem
Return the largest product of any non-empty contiguous subarray of nums. Values can be negative or zero.
Example: [2,3,-2,4] → 6; [-2,0,-1] → 0
Constraints: n ≤ 2·10⁴.
Track both the max and min product ending here — a negative number swaps them.
nums 2 3 -2 4
max 2 6 -2 4
min 2 3 -12 -48 best = 6
Complexity: O(n) time, O(1) space.
class Solution:
def maxProduct(self, nums: List[int]) -> int:
best = hi = lo = nums[0]
for x in nums[1:]:
cands = (x, hi * x, lo * x)
hi, lo = max(cands), min(cands)
best = max(best, hi)
return best
assert Solution().maxProduct([2, 3, -2, 4]) == 6
assert Solution().maxProduct([-2, 0, -1]) == 0
assert Solution().maxProduct([-2, 3, -4]) == 24
class Solution {
public int maxProduct(int[] nums) {
int best = nums[0], hi = nums[0], lo = nums[0];
for (int i = 1; i < nums.length; i++) {
int x = nums[i], a = hi * x, b = lo * x;
hi = Math.max(x, Math.max(a, b));
lo = Math.min(x, Math.min(a, b));
best = Math.max(best, hi);
}
return best;
}
}
func maxProduct(nums []int) int {
best, hi, lo := nums[0], nums[0], nums[0] // largest and smallest product ending here
for _, x := range nums[1:] {
a, b := hi*x, lo*x // a negative x swaps the roles of hi and lo
hi, lo = max(x, a, b), min(x, a, b)
best = max(best, hi)
}
return best
}