找出一个序列中乘积最大的连续子序列(至少包含一个数)。
您在真实的面试中是否遇到过这个题?
Yes
样例
比如, 序列 [2,3,-2,4] 中乘积最大的子序列为 [2,3] ,其乘积为6。
标签 Expand
相关题目 Expand
您在真实的面试中是否遇到过这个题?
Yes
样例
比如, 序列 [2,3,-2,4] 中乘积最大的子序列为 [2,3] ,其乘积为6。
标签 Expand
相关题目 Expand
解题思路
:
简单动态规划:
•用数组positive_max[i]维护原始数组前i个数的子数组乘积中正数的最大值
•用数组negative_min[i]维护原始数组前i个数的子数组乘积中负数的最小值
状态转移方程为:
if A[x] > 0:
positive_max[x] = max(positive_max[x - 1] * A[x], A[x])
negative_min[x] = negative_min[x - 1] * A[x]
elif A[x] < 0:
positive_max[x] = negative_min[x - 1] * A[x]
negative_min[x] = min(positive_max[x - 1] * A[x], A[x])
public class Solution {
/**
* @param nums: an array of integers
* @return: an integer
*/
public int maxProduct(int[] nums) {
// write your code here
int posmax = nums[0];
int posmin = nums[0];
int resmax = nums[0];
for(int i=1;i<nums.length;i++){
int a = posmax*nums[i];
int b = posmin*nums[i];
posmax = Math.max(Math.max(a, b), nums[i]);
posmin = Math.min(Math.min(a, b), nums[i]);
resmax = Math.max(resmax, posmax);
}
return resmax;
}
}