题目描述:
给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
示例 1: 输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2: 输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-subarray
解题方案:
思路
- 标签:动态规划 遍历数组时计算当前最大值,不断更新
- 令currMax为当前最大值,则当前最大值为 currMax = Math.max(n ,Math.max(m,x));
- 由于存在负数,那么会导致最大的变最小的,最小的变最大的。因此还需要维护当前最小值currMin,currMin = Math.min(n,Math.min(m,x));
- 时间复杂度:O(n)
代码
java版本
class Solution {
public int maxProduct(int[] nums) {
int len = nums.length;
if(len == 0)
return 0;
int res=nums[0], currMax = nums[0], currMin = nums[0],max,min;
for(int i = 1; i < len; i++) {
int x = nums[i]; //x赋值只是便于下面书写
//max,min解决了x为正负两种情况的最大值
max = currMax * x;
min = currMin * x;
currMax = Math.max(max ,Math.max(min,x));
currMin = Math.min(max,Math.min(min,x));
res = Math.max(currMax,res);
}
return res;
}
}
c++版本
#include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
int maxProduct(vector<int>& nums) {
int len = nums.size();
if(len == 0)
return 0;
int res=nums[0], currMax = nums[0], currMin = nums[0],max,min;
for(int i = 1; i < len; i++) {
int x = nums[i];
max = currMax * x;
min = currMin * x;
currMax = max(max ,max(min,x));
currMin = min(max,min(min,x));
//cout << currMax << " " << currMin << endl;
res = max(currMax,res);
}
return res;
}
int main()
{
vector<int> a;
a.push_back(-1);
a.push_back(-2);
a.push_back(-9);
a.push_back(-6);
cout << maxProduct(a) << endl;
return 0;
}