LeetCode 1567. Maximum Length of Subarray With Positive Product

原题链接在这里:https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/

题目:

Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.

A subarray of an array is a consecutive sequence of zero or more values taken out of that array.

Return the maximum length of a subarray with positive product.

Example 1:

Input: nums = [1,-2,-3,4]
Output: 4
Explanation: The array nums already has a positive product of 24.

Example 2:

Input: nums = [0,1,-2,-3,-4]
Output: 3
Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.
Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.

Example 3:

Input: nums = [-1,-2,-3,0,1]
Output: 2
Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].

Constraints:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109

题解:

When negative * negative, it becomes positive.

We keep a positive and negative to track with the current number, the longest length.

If we encounter 0, then both are set back to 0.

If we encounter positive number, then positive++. negative++ if we have seen a negative before.

If we encounter negative number, then swap. But note, if we have seen a negative before, then positive = negative + 1, otherwise if negative = 0, then psotive = 0.

Time Complexity: O(n). n = nums.length.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int getMaxLen(int[] nums) {
 3         int res = 0;
 4         int positive = 0;
 5         int negative = 0;
 6         for(int num : nums){
 7             if(num == 0){
 8                 positive = 0;
 9                 negative = 0;
10             }else if(num > 0){
11                 positive++;
12                 negative = negative == 0 ? 0 : negative + 1;
13             }else{
14                 int temp = positive;
15                 positive = negative == 0 ? 0 : negative + 1;
16                 negative = temp + 1;
17             }
18             
19             res = Math.max(res, positive);
20         }
21         
22         return res;
23     }
24 }

 

posted @ 2022-08-12 07:58  Dylan_Java_NYC  阅读(134)  评论(0编辑  收藏  举报