-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1493.py
More file actions
50 lines (36 loc) · 1.38 KB
/
1493.py
File metadata and controls
50 lines (36 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 1493. Longest Subarray of 1's After Deleting One Element
"""
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.
"""
class Solution:
def longestSubarray(self, nums: list[int]) -> int:
left = 0
zeros = 0
max_len = 0
for right in range(len(nums)):
if nums[right] == 0:
zeros += 1
while zeros > 1:
if nums[left] == 0:
zeros -= 1
left += 1
max_len = max(max_len, right - left + 1)
return max_len - 1 # delete one element
if __name__ == "__main__":
sol = Solution()
print(sol.longestSubarray([1,1,0,1])) # 3
print(sol.longestSubarray([0,1,1,1,0,1,1,0,1])) # 5
print(sol.longestSubarray([1,1,1])) # 2