LeetCode 152. Maximum Product Subarray

Given an integer array nums, find asubarray that has the largest product, and return the product.

The test cases are generated so that the answer will fit in a 32-bit integer.

Note that the product of an array with a single element is the value of that element.

Example 1:

复制代码
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

复制代码
Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

Constraints:

  • 1 <= nums.length <= 2 * 104
  • -10 <= nums[i] <= 10
  • The product of any subarray of nums is guaranteed to fit in a 32-bit integer.

自己做就是不会,虽然其实挺直观的。

思路和53有点像,需要记录遍历到当前的最大值,以及最后的结果。但因为这题是乘法,可能会出现负负得正的情况,所以有可能负负得正以后反而成为了更大值,因此需要同时记录当前的最大和当前的最小。对于遍历到当前这个数字i,它这会儿的最大值就是max(numsi, numsi * currMax, numsi * currMin),以及需要更新currMax和currMin。

复制代码
class Solution {
    public int maxProduct(int[] nums) {
        int currMin = nums[0];
        int currMax = nums[0];
        int result = nums[0];

        for (int i = 1; i < nums.length; i++) {
            int newMin = Math.min(nums[i], Math.min(currMin * nums[i], currMax * nums[i]));
            int newMax = Math.max(nums[i], Math.max(currMin * nums[i], currMax * nums[i]));

            currMin = newMin;
            currMax = newMax;

            result = Math.max(result, currMax);
        }

        return result;        
    }
}

根据gpt老师,还可以简化成如果当前数字是负数,就交换最大值和最小值。我自己没写代码,太懒了,贴gpt老师的答案好了。

复制代码
class Solution {
    public int maxProduct(int[] nums) {
        int maxProduct = 1;
        int minProduct = 1;
        int result = nums[0];

        for (int x : nums) {
            if (x < 0) {
                int temp = maxProduct;
                maxProduct = minProduct;
                minProduct = temp;
            }

            maxProduct = Math.max(x, maxProduct * x);
            minProduct = Math.min(x, minProduct * x);

            result = Math.max(result, maxProduct);
        }

        return result;
    }
}
相关推荐
Java展博21 分钟前
[Go 后端转场] 从 try-catch 到 if err != nil:写惯 Java 的人第一次上手最别扭的 4 件事
java·开发语言·golang
starzy199028 分钟前
Hadoop介绍总结:一张图理清组件、生态与版本
java·hadoop
yyuuuzz1 小时前
nginx 502 排查,先看上游超时那一行
android·java·运维·nginx·502
Java后端的Ai之路1 小时前
Java并发编程25-集合的线程安全
java·安全·面试
风落青芜1 小时前
数据结构:堆的概念与实现
c语言·开发语言·数据结构·算法
CoderYanger1 小时前
Java EE 进阶:9.MyBatis 操作数据库(进阶)(第一弹)
java·数据库·spring·面试·java-ee·tomcat·mybatis
码云社区2 小时前
Java租房平台源码方案:Vue 3房源审核、UniApp预约看房与房东管理
java·vue.js
codigger3 小时前
ThreadLocal 会内存泄露吗?
java·内存泄漏·threadlocal
挖掘狂人3 小时前
ThreadLocal 会内存泄露吗?
java·安全·架构
未秃头的程序猿4 小时前
给新模块加了个 @MapperScan,启动崩了,最后发现跟 MapperScan 没关系
java·后端·mybatis