当前位置:网站首页>leetcode:1567. Length of the longest subarray whose product is a positive number [dp[i] indicates the maximum length ending with I]

leetcode:1567. Length of the longest subarray whose product is a positive number [dp[i] indicates the maximum length ending with I]

2022-06-26 21:43:00 Review of the white speed Dragon King

 Insert picture description here

analysis

alike , We need the maximum length of the product of the longest negative number and the longest positive number
among dp[i] It means that the... Is selected i Maximum length in cases
Then we can deduce positive[i + 1] and negative[i + 1] The relationship between

if nums[i] > 0:
   positive[i] = positive[i - 1] + 1
   negative[i] = (negative[i - 1] + 1 if negative[i - 1] > 0 else 0)
elif nums[i] < 0:
   positive[i] = (negative[i - 1] + 1 if negative[i - 1] > 0 else 0)
   negative[i] = positive[i - 1] + 1
else:
   positive[i] = negative[i] = 0

If the current number is positive :
positive[i] It's the last one +1 that will do
negative[i] Words , If not before negative Words , Multiplying by an integer won't be negative, So it is 0; If so +1
If the current number is negative :
negative[i] If so, go directly to a positive number +1
positive[i] If there were no negative numbers before , At present, it is not a positive number , If any , direct +1
If it is 0
Two resets 0

ac code

class Solution:
    def getMaxLen(self, nums: List[int]) -> int:
        length = len(nums)
        positive, negative = [0] * length, [0] * length
        if nums[0] > 0:
            positive[0] = 1
        elif nums[0] < 0:
            negative[0] = 1
        
        maxLength = positive[0]
        for i in range(1, length):
            if nums[i] > 0:
                positive[i] = positive[i - 1] + 1
                negative[i] = (negative[i - 1] + 1 if negative[i - 1] > 0 else 0)
            elif nums[i] < 0:
                positive[i] = (negative[i - 1] + 1 if negative[i - 1] > 0 else 0)
                negative[i] = positive[i - 1] + 1
            else:
                positive[i] = negative[i] = 0
            maxLength = max(maxLength, positive[i])

        return maxLength


        

summary

dp[i] Said to i Longest ending xxx
Both positive and negative cases are considered here

原网站

版权声明
本文为[Review of the white speed Dragon King]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206262137595827.html