LeetCode解题 152:Maximum Product Subarray
Problem 152: Maximum Product Subarray [Medium]
Given an integer array nums
, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
来源:LeetCode
解题思路
使用动态规划思想。维护两个局部更新量max,min,当遇到负数时交换两个变量的值。同时维护一个全局更新量maxP,每次计算出新的max后更新一次maxP。
具体思路:
- 首先将max,min,maxP都初始化为nums[0]。
- 遍历nums,不断更新max,min,maxP,更新公式为:
m a x = max { m a x ∗ n u m s [ i ] , n u m s [ i ] } m i n = min { m i n ∗ n u m s [ i ] , n u m s [ i ] } m a x P = max { m a x P , m a x } max = \max\{max * nums[i], nums[i]\} \\ min = \min\{min * nums[i], nums[i]\} \\ maxP = \max\{maxP, max\} max=max{max∗nums[i],nums[i]}min=min{min∗nums[i],nums[i]}maxP=max{maxP,max} - 遍历中如果遇到nums[i]为负数的情况,需要调换max,min的值之后再进行更新,因为乘以负数会将之前的最大值变为最小值,最小值变为最大值。
- 最后返回maxP。
时间复杂度为 O ( n ) O(n) O(n),空间复杂度为 O ( 1 ) O(1) O(1)。
运行结果:
要点:动态规划
Solution (Java)
class Solution {
public int maxProduct(int[] nums) {
int N = nums.length;
if(N < 1) return 0;
if(N < 2) return nums[0];
int maxP = nums[0];
int max = nums[0];
int min = nums[0];
for(int i = 1; i < N; i++){
if(nums[i] < 0){
int temp = max;
max = min;
min = temp;
}
max = Math.max(max * nums[i], nums[i]);
min = Math.min(min * nums[i], nums[i]);
maxP = Math.max(maxP, max);
}
return maxP;
}
}