当前位置: 代码迷 >> 综合 >> Leetcode 1567. Maximum Length of Subarray With Positive Product (python)
  详细解决方案

Leetcode 1567. Maximum Length of Subarray With Positive Product (python)

热度:38   发布时间:2023-11-26 06:38:34.0

Leetcode 1567. Maximum Length of Subarray With Positive Product

  • 题目:
  • 解法1:
  • 解法2:two pass

题目:

在这里插入图片描述

解法1:

这种判断正负的题目往往都是通过正负得负,负负得正这样的方式来进行交换得到的,之前也有过类似的题目:比如Leetcode 152 Maximum Product Subarray

这题具体的解析如下:
The main idea here is to keep a count of running positive array length and negative array length.

if nums[i] < 0, since any negative number would make the positive array as negative and a negative array as positive, we swap the positive and negative length, and increase the negativeLength and if the positive length array > 0, we increament that as well.

if nums[i] == 0, we reset positive and negative length to 0

else if nums[i] > 0, we increament the positive length and if there is a negative product array, we increment negative length, since any positive number will keep the negative array as negative and positive array as positive.

We keep updating the maxPositive for every number, and then return it in the end.

代码:

class Solution:def getMaxLen(self, nums: List[int]) -> int:posi_len = 0nega_len = 0ans = 0for num in nums:if num==0:posi_len=nega_len = 0elif num<0:posi_len,nega_len = nega_len,posi_lennega_len += 1if posi_len>0:posi_len += 1 else:posi_len += 1if nega_len>0:nega_len += 1ans = max(ans,posi_len)return ans

解法2:two pass

这种解法虽然很新奇,但是不好理解,建议记第一种

class Solution:def getMaxLen(self, nums: List[int]) -> int:p = s = 1start = 0end = len(nums)mxp = mxe = 0for i in range(len(nums)):p = (p or 1 ) * nums[i]if p == 0:start = i + 1if p > 0:mxp = max(i - start + 1, mxp)for i in range(len(nums) - 1, -1, -1):            s = (s or 1 ) * nums[i]if s == 0:end = i if s > 0:mxe = max(end - i, mxe)return max(mxp, mxe)

参考:
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/901314/Java-O(n)-time-O(1)-space-easy-to-understand-with-explaination
https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/902815/Python-Two-Pass-Solution

  相关解决方案