📘
Maximum Product Subarray
MediumDynamic Programming
Given an integer array nums, find a subarray that has the largest product and return the product.
Example:
Input:
2,3,-2,4
Output:
6
Reasoning:
- We start by examining all possible subarrays:
[2], [2, 3], [2, 3, -2], [2, 3, -2, 4], [3], [3, -2], [3, -2, 4], [-2], [-2, 4], [4] - Then, we calculate the product of each subarray:
[2], [2*3=6], [2*3*-2=-12], [2*3*-2*4=-48], [3], [3*-2=-6], [3*-2*4=-24], [-2], [-2*4=-8], [4] - The subarray with the largest product is
[2, 3]with a product of 2⋅3=6 - The final output is the product of this subarray, which is 6
Constraints:
- 1 <= len(nums) <= 2 * 10^4
- -10 <= nums[i] <= 10
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.