LeetCode(152):乘积最大子序列 Maximum Product Subarray(Java)

234 篇文章 1 订阅
177 篇文章 0 订阅

2019.8.18 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

之前做过最大子序和LeetCode(53):最大子序和 Maximum Subarray(Java),这道题是最大子序积。这题也差不多,一维数组题大部分用动态规划的思路做。

由于数组存在负数,需要同时维护一个最大值max和一个最小值min,动态遍历每一个值i。动态更新的方程是

max = Math.max(nums[idx], max * nums[idx]);
min = Math.min(nums[idx], min * nums[idx]);

遇到负数则交换max和min,遇到0会自动更新为0.


传送门:乘积最大子序列

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

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

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

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


/**
 *
 * Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
 * 给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
 *
 */

public class MaximumProductSubarray {
    public int maxProduct(int[] nums) {
        int result = nums[0];
        int max = nums[0];
        int min = nums[0];

        int idx = 1;
        while(idx < nums.length){
            //存在复数时将最大值和最小值交换
            if(nums[idx] < 0){
                int temp = max;
                max = min;
                min = temp;
            }
            max = Math.max(nums[idx], max * nums[idx]);
            min = Math.min(nums[idx], min * nums[idx]);
            result = result > max ? result : max;
            idx++;
        }

        return result;
    }
}




#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值