【leetcode-152】 乘积最大子序列

给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。

示例 1:

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

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

 

由于存在负数,那么会导致最大的变最小的,最小的变最大的。因此还需要维护当前最小值imin

max表示以当前节点为终结节点的最大连续子序列乘积 min表示以当前节点为终结节点的最小连续子序列乘积

我们只要记录前i的最小值, 和最大值, 那么 dp[i] = max(nums[i] * pre_max, nums[i] * pre_min, nums[i])

class Solution {
    public int maxProduct(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        int res = nums[0];
        int pre_max = nums[0];
        int pre_min = nums[0];
        for (int i = 1; i < nums.length; i++) {
            int cur_max = Math.max(Math.max(pre_max * nums[i], pre_min * nums[i]), nums[i]);
            int cur_min = Math.min(Math.min(pre_max * nums[i], pre_min * nums[i]), nums[i]);
            res = Math.max(res, cur_max);
            pre_max = cur_max;
            pre_min = cur_min;
        }
        return res;
    }
}

 

我:

    public int maxProduct(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int max = nums[0];
        int pre_max = nums[0];
        int pre_min = nums[0];
        for (int i=1;i<nums.length;i++) {
            int cur_max = Math.max(Math.max(pre_max*nums[i],pre_min*nums[i]),nums[i]);
            int cur_min = Math.min(Math.min(pre_max*nums[i],pre_min*nums[i]),nums[i]);
            max = Math.max(max,cur_max);
            pre_max = cur_max;
            pre_min = cur_min;
        }
        return max;
    }

 

posted @ 2019-09-06 13:48  twoheads  阅读(225)  评论(0编辑  收藏  举报