Algo-Sim › Dynamic Programming

Maximum Product Subarray

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Largest product of a contiguous subarray: track the largest and the smallest product ending at each index, because a negative swaps them.

Problem

Given an integer array nums, return the largest product of any non-empty contiguous subarray. The array may contain negative numbers and zeros, so the best subarray is not always the one with the largest numbers.

Constraints

Edge cases to test

Follow-up questions

Why track the minimum too?
Multiplying the smallest (most negative) product by a negative number can make the largest one.
Is there a prefix–suffix trick?
The answer is the best running product from the left or from the right, restarting after zeros: O(n), O(1).

Solution

Java

public int maxProduct(int[] nums) {
    int curMax = nums[0], curMin = nums[0], best = nums[0];
    for (int i = 1; i < nums.length; i++) {
        int x = nums[i];
        int a = curMax * x, b = curMin * x;
        curMax = Math.max(x, Math.max(a, b));
        curMin = Math.min(x, Math.min(a, b));
        best = Math.max(best, curMax);
    }
    return best;
}

Python

def max_product(nums):
    cur_max = cur_min = best = nums[0]
    for x in nums[1:]:
        a, b = cur_max * x, cur_min * x
        cur_max = max(x, a, b)
        cur_min = min(x, a, b)
        best = max(best, cur_max)
    return best

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int maxProduct(vector<int> &nums) {
        int curMax = nums[0], curMin = nums[0], best = nums[0];
        for (int i = 1; i < int(nums.size()); i++) {
            int x = nums[i];
            int a = curMax * x, b = curMin * x;
            curMax = std::max(x, std::max(a, b));
            curMin = std::min(x, std::min(a, b));
            best = std::max(best, curMax);
        }
        return best;
    }
};

More Dynamic Programming problems