Skip to content

Commit 83db51a

Browse files
committed
Add solution for longest subarray of 1s after deleeting one element
1 parent 1e4d8fc commit 83db51a

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# 1493. Longest Subarray of 1's After Deleting One Element
2+
3+
## Description
4+
See https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/description/
5+
6+
## Problem
7+
Given a binary array `nums`, you should delete one element from it.
8+
9+
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.
10+
11+
## Example 1
12+
13+
```
14+
Input: nums = [1,1,0,1]
15+
Output: 3
16+
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.
17+
```
18+
19+
## Example 2
20+
21+
```
22+
Input: nums = [0,1,1,1,0,1,1,0,1]
23+
Output: 5
24+
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].
25+
```
26+
27+
## Example 3
28+
29+
```
30+
Input: nums = [1,1,1]
31+
Output: 2
32+
Explanation: You must delete one element.
33+
```
34+
35+
## Constraints
36+
37+
```
38+
Input: nums = [0,1,1,1,0,1,1,0,1]
39+
Output: 5
40+
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].
41+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
def longest(nums: list[int]) -> int:
2+
zeros, left, right = 0, 0, 0
3+
while right < len(nums):
4+
if nums[right] == 0:
5+
zeros += 1
6+
if zeros > 1:
7+
left += 1
8+
if nums[left - 1] == 0:
9+
zeros -= 1
10+
right += 1
11+
return (right - left) - 1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from longestsubarray import longest
2+
3+
4+
def test_example_1():
5+
nums = [1, 1, 0, 1]
6+
assert longest(nums) == 3
7+
8+
9+
def test_example_2():
10+
nums = [0, 1, 1, 1, 0, 1, 1, 0, 1]
11+
assert longest(nums) == 5
12+
13+
14+
def test_example_3():
15+
nums = [1, 1, 1, 1, 1]
16+
assert longest(nums) == 4
17+
18+
19+
def test_example_4():
20+
nums = [0, 0, 0, 0, 0]
21+
assert longest(nums) == 0
22+
23+
24+
def test_example_6():
25+
nums = [1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1]
26+
assert longest(nums) == 5

0 commit comments

Comments
 (0)