算法-----------乘积最大子数组(Java版本)

题目:

给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。

 

示例 1:

输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:

输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。

解决方法

class Solution {
    public int maxProduct(int[] nums) {
        int max = Integer.MIN_VALUE,cMax = 1,cMin = 1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] < 0) {
                int temp;
                temp = cMax;
                cMax = cMin;
                cMin = temp;
            }
            cMax = Math.max(nums[i],cMax*nums[i]);
            cMin = Math.min(nums[i],cMin*nums[i]);
            max = Math.max(max,cMax);
        }
        return max;

    }
}

解题思路

因为可能有负数的存在,所以,最大值可能会变成最小值,最小值也可能会变成最大值,所以,我们在每一步都需要保存一个最大值,一个最小值。

这种题目属于动态规划,会有很多种组合,然后求最优解。要多练习,培养思维。

你可能感兴趣的:(java,算法)