152 乘积最大子数组

152 乘积最大子数组

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

测试用例的答案是一个 32-位 整数。

子数组 是数组的连续子序列。

示例:

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

思考:

  • Imax、Imin、max
public class Solution {

    /**
     * 乘积最大子数组
     * 注意:子数组指数组的连续子序列
     * 输入: nums = [2,3,-2,4]
     * 输出: 6
     */
    public int maxProduct(int[] nums) {
        // 由于存在负数,导致子数组乘积从最大变成最小
        // 所以每一位数组元素都需要存当前位置的最大乘积、最小乘积
        // iMax:表示0到i的最大乘积
        int iMax = 1;
        // iMin:表示0到i的最小乘积
        int iMin = 1;

        int max = Integer.MIN_VALUE;
        for (int num : nums) {
            // 遇到负数,交换iMax、iMin
            if (num < 0) {
                int temp = iMax;
                iMax = iMin;
                iMin = temp;
            }

            iMax = Math.max(iMax * num, num);
            iMin = Math.min(iMin * num, num);

            max = Math.max(max, iMax);
        }
        return max;
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, -2, 4};
        Solution solution = new Solution();
        System.out.println(solution.maxProduct(nums));
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值