算法——乘积最大的连续子数组

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

解题思路:

  • 再计算过程中,会产生负数和正数,需要同时保存最小的负数和最大的整数,因为乘起来的时候都有可能是产生更大的结果。
  • 利用两个变量,一个存储最大值,一个存储最小值,每次遍历的都是都更新这个两个值,然后比较答案。
class Solution {
    public int maxProduct(int[] nums) {
        int res = nums[0];
        int f = nums[0], g = f;

        for(int i = 1; i < nums.length; i++) {
            int nf = f * nums[i];
            int ng = g * nums[i];
            f = Math.max(nums[i], Math.max(nf, ng));
            g = Math.min(nums[i], Math.min(nf, ng));

            res = Math.max(res, f);
        }
        return res;
    }
}
posted @ 2020-11-24 16:13  lippon  阅读(226)  评论(0编辑  收藏  举报