题解 | #连续子数组的最大乘积#
连续子数组的最大乘积
http://www.nowcoder.com/practice/abbec6a3779940aab2cc564b22d36859
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型
*/
public int maxProduct (int[] nums) {
// write code here
// 暴力破解
/*
int num = 0;
int tmp = 1;
int max = Integer.MIN_VALUE;
for (int i = 1; i <= nums.length; i++) {
num = nums[i - 1]; // 初始化
for (int j = i; j >= 1; j--) {
tmp *= nums[j - 1];
num = Math.max(num, tmp);
}
tmp = 1;
max = Math.max(max, num);
}
return max;
*/
// 动态规划
int previousMaximum = nums[0];
int previousMinimum = nums[0];
int currentMaximum = nums[0];
int currentMinimum = nums[0];
int rs = nums[0];
for (int i = 2; i <= nums.length; i++) {
currentMaximum = Math.max(Math.max(nums[i-1], previousMaximum*nums[i-1]), previousMinimum*nums[i-1]);
currentMinimum = Math.min(Math.min(nums[i-1], previousMaximum*nums[i-1]), previousMinimum*nums[i-1]);
rs = Math.max(rs, currentMaximum);
previousMaximum = currentMaximum;
previousMinimum = currentMinimum;
}
return rs;
}
}