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

Hiring now

Visa has 638 open roles right now

Also hiring: PhonePe

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Software Engineer Intern

    GB - London, United Kingdom

  • Sr. Software Engineer (3+ yrs, DevOps, Cloud, Coding, Infra)

    IN - Bengaluru, India

  • Sr Software Engineer (3-5 yrs of exp - Full stack development, Java, React, Gen AI)

    IN - Bengaluru, India

Or practice this question first

Next question