
思路源自
【小白都能听懂的算法课】【力扣】【Leetcode152】乘积最大子数组|动态规划|数组
动态规划,每一步求出以当前数结尾的最大乘积和最小乘积(因为存在负数)
java
class Solution {
public int maxProduct(int[] nums) {
int result=nums[0];
int curMax = nums[0], curMin = nums[0];
for (int i = 1; i < nums.length; i++) {
int tempMax = curMax, tempMin = curMin;
curMax = Math.max(Math.max(tempMax * nums[i], tempMin * nums[i]), nums[i]);
curMin = Math.min(Math.min(tempMax * nums[i], tempMin * nums[i]), nums[i]);
result = Math.max(result, curMax);
}
return result;
}
}