当前位置:网站首页>LeetCode 152. Product maximum subarray daily question

LeetCode 152. Product maximum subarray daily question

2022-07-07 16:58:00 @Little safflower

Problem description

Give you an array of integers nums , Please find the non empty continuous subarray with the largest product in the array ( The subarray contains at least one number ), And returns the product of the subarray .

The answer to the test case is  32- position Integers .

Subarray Is a continuous subsequence of an array .

Example 1:

Input : nums = [2,3,-2,4]
Output : 6
explain :  Subarray [2,3] There is a maximum product 6.
Example 2:

Input : nums = [-2,0,-1]
Output : 0
explain :  The result can't be 2, because [-2,-1] It's not a subarray .
 

Tips :

1 <= nums.length <= 2 * 104
-10 <= nums[i] <= 10
nums The product of any prefix or suffix of Guarantee   It's a 32- position Integers

source : Power button (LeetCode)
link :https://leetcode.cn/problems/maximum-product-subarray
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

Java

class Solution {
    public int maxProduct(int[] nums) {
        if(nums.length == 1) return nums[0];
        int ans = 0;
        int positive = 1;
        int negative = 1;

        for(int n : nums){
            if(positive <= 0) positive = 1;
            if(negative >= 0) negative = 1;

            if(n < 0){
                int t = negative;
                negative = positive * n;
                positive = t * n;
            }else {
                negative *= n;
                positive *= n;
            }
            if(positive > ans) ans = positive;
        }
        return ans;
    }
}

 

原网站

版权声明
本文为[@Little safflower]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071512071363.html