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;
    }
}
相关推荐
余额瞒着我当琳1 小时前
C++异常,异常的概念,异常抛出与捕获,RAII 和智能指针的设计思路,C++标准库一些指针的使用
java·开发语言·c++·算法
2601_970703831 小时前
除湿机原理研究报告:一台机器在物理上能走多远
大数据·数据结构·算法·数据库架构·推荐算法
信奥卷王1 小时前
[GESP202312 六级] 工作沟通(含视频)
算法
♡すぎ♡1 小时前
SWE 的原理解析
算法·计算机图形学·swe
花间相见1 小时前
【macOS开发环境:Java配置】—— Mac上的Java版本管理-SDKMAN安装、多版本切换与项目实战
java·架构·个人开发
AiNightVision1 小时前
星光级 是什么?——星光级摄像机是什么?0.001Lux 照度门槛与选型真相
人工智能·算法·车载系统·自动驾驶·无人机·视频·智能硬件
骑着蜗牛撵大象3271 小时前
大模型 SDK 编译就崩?用 CMakeLists 把 httplib、JSON 与 OpenSSL 装配成可复用的 ChatServer
android·java·c++·http·json·cmake·大模型sdk
若亦_1 小时前
排序>>选择排序
数据结构·算法·排序算法