[leetcode] 1493. Longest Subarray of 1‘s After Deleting One Element

Description

Given a binary array nums, you should delete one element from it.

Return the size of the longest non-empty subarray containing only 1’s in the resulting array.

Return 0 if there is no such subarray.

Example 1:

Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.

Example 2:

Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].

Example 3:

Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.

Example 4:

Input: nums = [1,1,0,0,1,1,1,0,1]
Output: 4

Example 5:

Input: nums = [0,0,0]
Output: 0

Constraints:

  1. 1 <= nums.length <= 10^5
  2. nums[i] is either 0 or 1.

分析

题目的意思是:给定一个只包含0,1的数组,然后删除一个0,求组成的最长1的序列,这道题我一开始没什么思路,看了提示以后发现可以维护一个包含一个0的滑动窗口,如果能够想到这点,就能够做出来了。l记录左边界,r记录右边界;当r为0的时候,要判断l边界是否为0,为0,则只需要向右移动一步;否则要移动到0的位置,然后再向右移动一步。

代码

class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        n=len(nums)
        l=0
        r=0
        cnt=0
        max_len=0
        while(r<n):
            if(nums[r]==0):
                cnt+=1
                if(cnt>1):
                    while(nums[l]==1):
                        l+=1
                    l+=1
                    cnt-=1
            
            r+=1
            max_len=max(max_len,r-l-1)
        return max_len
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值