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
- 1 ≤ nums.length ≤ 2 · 10⁴
- −10 ≤ nums[i] ≤ 10
- Every prefix and suffix product fits in a 32-bit integer
Edge cases to test
- A single negative number
- Zeros split the array
- Two negatives make a positive
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 bestC++
#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
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)