刷题-Leetcode-152. 乘积最大子数组

152. 乘积最大子数组

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-subarray/

题目描述

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

示例 1:

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

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

题目分析

此题和力扣53题很像,要注意的是此题要维护最小的值,因为负数和负数相乘就变成正数。

class Solution {
    
    
    public int maxProduct(int[] nums) {
    
    
        int maxdp[] = new int[nums.length];
        int mindp[] = new int[nums.length];
        maxdp[0] = nums[0];
        mindp[0] = nums[0];
        int res = maxdp[0];
        for(int i=1;i<nums.length;i++){
    
    
            maxdp[i] = max(nums[i]*maxdp[i-1],nums[i]*mindp[i-1],nums[i]);
            mindp[i] = min(nums[i]*maxdp[i-1],nums[i]*mindp[i-1],nums[i]);
            res = res > maxdp[i] ? res : maxdp[i];
        }
        return res;
    }
    public int max(int a,int b,int c){
    
    
        a = a>b?a:b;
        return a>c?a:c;
    }
    public int min(int a,int b,int c){
    
    
        b = a>b?b:a;
        return b>c?c:b;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42771487/article/details/113443907