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 <= nums.length <= 10^5
- 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