LeetCode-152. 乘积最大子数组

题目

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

示例

示例 1:

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

示例 2:

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

解题思路

思想:动态规划

  1. 遍历整个数组,计算当前最大值和最小值
  2. 当出现负数时,最大值需要和最小值交换(因为负数会使最大值变小,最小值变大)
  3. 每次遍历一个元素,记录当前最大值,遍历完数组后,返回记录的值即可。

代码实现

class Solution {
    public int maxProduct(int[] nums) {

         int ans = Integer.MIN_VALUE;
        int currentMax = 1;
        int currentMin = 1;

        for (int i = 0; i < nums.length; i++) {
            //出现负数,最大值和最小值交换
            if( nums[i] < 0){
                int temp = currentMax;
                currentMax = currentMin;
                currentMin = temp;
            }
            //记录当前最大值和最小值
            currentMax = Math.max(currentMax*nums[i], nums[i]);
            currentMin = Math.min(currentMin*nums[i], nums[i]);
            ans = Math.max(currentMax, ans);
        }

        return ans;
    }
}

复杂度分析

  • 时间复杂度:程序一次循环遍历了 n u m s nums nums,故时间复杂度为 O ( n ) O(n) O(n)

  • 空间复杂度:只使用常数个临时变量作为辅助空间,与 n n n 无关,故空间复杂度为 O ( 1 ) O(1) O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值