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

这篇博客探讨了LeetCode的1567题,旨在找到数组中乘积为正数的最长子数组长度。解决方案包括两种方法:一种通过维护正负数数组长度来迭代更新,另一种双遍历解法,虽然复杂但能解决问题。建议重点掌握第一种解法。
摘要由CSDN通过智能技术生成

Leetcode 1567. Maximum Length of Subarray With Positive Product

题目:

在这里插入图片描述

解法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 =
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值