Maximum Product Subarray
Maximum Product Subarray is a Medium Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Dynamic Programming (DP) Patterns pattern, in the 1D Array (Kadane's Algorithm for Max/Min Subarray) subpattern.
Problem statement
Given an integer array nums, find a subarray that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6.
Example 2:
Input: nums = [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
Constraints:
- 1 <= nums.length <= 2 104
- -10 <= nums[i] <= 10
- The product of any subarray of nums is guaranteed to fit in a 32-bit integer.
Topics and companies
Topics: Array, Dynamic Programming.
Reported in interviews at Amazon, LinkedIn, Google, Apple, Facebook, Akuna Capital.
How to practise Maximum Product Subarray on Thita.ai
Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(n) time and O(1) space.
Open Maximum Product Subarray in the code editor, or read the Maximum Product Subarray editorial for a worked solution with its approach and complexity analysis.
Where Maximum Product Subarray sits in the DSA pattern sheet
- Dynamic Programming (DP) Patterns pattern guide
- 1D Array (Kadane's Algorithm for Max/Min Subarray) subpattern
- The full DSA patterns sheet
- All coding practice problems
Problems related to Maximum Product Subarray
Other problems that use the same 1D Array (Kadane's Algorithm for Max/Min Subarray) and Dynamic Programming (DP) Patterns techniques:
- Maximum Absolute Sum of Any Subarray — Medium, same subpattern
- Maximum Subarray — Medium, same subpattern
- Maximum Sum Circular Subarray — Medium, same subpattern
- Best Time to Buy and Sell Stock — Easy, same pattern
- Best Time to Buy and Sell Stock II — Medium, same pattern
- Best Time to Buy and Sell Stock III — Hard, same pattern
Opening the problem
Progress is saved as you study.