算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个号后续每天带大家做一道算法题,题目就从LeetCode上面选 !今天和大家聊的问题叫做 乘积最大子数组,我们先来看题面:https://leetcode-cn.com/problems/maximum-product-subarray/

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] 不是子数组。

 

 

解题

思路: 求最大值,可以看成求被0拆分的各个子数组的最大值。当一个数组中没有0存在,则分为两种情况:1.负数为偶数个,则整个数组的各个值相乘为最大值;2.负数为奇数个,则从左边开始,乘到最后一个负数停止有一个“最大值”,从右边也有一个“最大值”,比较,得出最大值。

class Solution {
    public int maxProduct(int[] nums) {
int a=1;
        int max=nums[0];
        for(int num:nums){
            a=a*num;
            if(max<a){
                max=a;
            }
            if(num==0){
                a=1;
            }
        }
        a=1;
        for(int i=nums.length-1;i>=0;i--){
            a=a*nums[i];
            if(max<a){
                max=a;
            }
            if(nums[i]==0){
                a=1;
            }
        }
        return max;
    }
}

好了,今天的文章就到这里。

​LeetCode刷题实战152:乘积最大子数组_IT