LeetCode_Array_152. Maximum Product Subarray乘积最大子数组(C++/Java)

目录

1,题目描述

英文描述

中文描述

2,解题思路

3,AC代码

C++

Java

4,解题过程

第一博

第二搏


1,题目描述

英文描述

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

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

中文描述

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

示例 1:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2,解题思路

参考@画手大鹏【画解算法:152. 乘积最大子序列】

有几个关键点:

1,是整数数组,也就是说只要不出现0,那么乘积结果的绝对值是不会减小的;

2,最大值和最小值是会互换的,最大值遇到一个负数便会成为最小值,同样最小值遇到一个负数便会成为最大值。所以为了计算出结果,需要保留最大值和最小值;

3,iMax = max(iMax * nums[i], nums[i]),其中iMax初始值为1;(iMin同理)

3,AC代码

C++

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int ans = INT_MIN, iMax = 1, iMin = 1;  // ans最终答案 iMax当前最大值 iMin当前最小值
        for(int i = 0; i < nums.size(); i++){
            if(nums[i] < 0) {
                swap(iMax, iMin);
            }
            iMax = max(iMax * nums[i], nums[i]);
            iMin = min(iMin * nums[i], nums[i]);
            ans = max(iMax, ans);
        }
        return ans;
    }
};

Java

class Solution {
    public int maxProduct(int[] nums) {
        int ans = Integer.MIN_VALUE, iMax = 1, iMin = 1;
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] < 0) {
                int tem = iMax;
                iMax = iMin;
                iMin = tem;
            }
            iMax = Math.max(iMax * nums[i], nums[i]);   // 更新当前最大值
            iMin = Math.min(iMin * nums[i], nums[i]);   // 更新当前最小值
            ans = Math.max(ans, iMax);                  // 更新ans
        }
        return ans;
    }
}

4,解题过程

第一博

野蛮遍历。时间O(N^2),不出意外超时了

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int ans = INT_MIN;
        for(int i = 0; i < nums.size(); i++){
            int tem = nums[i];
            ans = max(ans, tem);
            for(int j = i + 1; j < nums.size(); j++){
                tem *= nums[j];
                ans = max(ans, tem);
            }
        }
        return ans;
    }
};

第二搏

参考大佬的解法,同时记录最大值和最小值(因为最大值遇到一个负数可能变成最小值,同样,最小值遇到一个负数也可能会变成最大值)。并且采用动态规划的思想,利用前一步的计算结果,降低运算耗时。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值