Maximum Product Subarray in an Array

Asked atCisco MerakiMicrosoftPhonePeVisa
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given an integer array nums. Find the **subarray **with the largest product, and return the **product **of the elements present in that subarray.

A **subarray **is a **contiguous **non-empty **sequence **of elements within an array.

Input: nums = [4, 5, 3, 7, 1, 2] Output: 840 Explanation: The largest product is given by the whole array itself

Input: nums = [-5, 0, -2] Output: 0 Explanation: The largest product is achieved with the following subarrays [0], [-5, 0], [0, -2], [-5, 0, -2].

Input: nums = [1, -2, 3, 4, -4, -3]

  • 1 <= nums.length <= 104
  • -10 <= nums[i] <= 10
  • -109 <= product of any prefix or suffix of nums <= 109

cpp

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        
    }
};

java

class Solution {
    public int maxProduct(int[] nums) {
        
    }
}

python

class Solution:
    def maxProduct(self, nums):

javascript

class Solution {
    maxProduct(nums) {

    }
}

csharp

public class Solution
{
    public int MaxProduct(List<int> nums)
    {
        
    }
}

go

func maxProduct(nums []int) int {
	//your code goes here
}
Stuck? Show a way to structure it+
  1. 01Track both the maximum and minimum product of a non-empty subarray ending at the current index.
  2. 02For each value, compare starting fresh with extending the previous maximum or minimum.
  3. 03Update the global answer from the new ending maximum.
  4. 04Explain how zeros reset the running states and negatives swap their roles.

Reference answer

Then expect these follow-ups

  • How would you also return the boundaries of the optimal subarray?

    Tests: state reconstruction

  • Why is tracking the minimum product necessary?

    Tests: invariant understanding

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question