Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-067

Maximum Product Subarray

Problem

Return the largest product of a non-empty contiguous subarray of nums.

Track both the maximum and minimum product ending at the current position, since multiplying a negative minimum by a negative value can create the new maximum. Return 0 for an empty list.

Hint

Keep the running minimum too: a very negative product can flip into the best answer.

Test cases

case 1
in: [[2,3,-2,4]]
expected: 6
case 2
in: [[-2,0,-1]]
expected: 0
case 3
in: [[-2,3,-4]]
expected: 24
case 4
in: [[-2]]
expected: -2
case 5
in: [[0,2]]
expected: 2
case 6
in: [[]]
expected: 0
Starter codePython
def max_product(nums):
    # Your code here
    pass

6 test cases · run your code against them in the editor