-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1004.py
More file actions
79 lines (55 loc) · 1.79 KB
/
1004.py
File metadata and controls
79 lines (55 loc) · 1.79 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# 1004. Max Consecutive Ones III
"""Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.
Example 1:
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Explanation: [1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
Output: 10
Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined."""
from typing import List
class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
left = 0
zeros = 0
max_len = 0
for right in range(len(nums)):
if nums[right] == 0:
zeros += 1
while zeros > k:
if nums[left] == 0:
zeros -= 1
left += 1
max_len = max(max_len, right - left + 1)
return max_len
# Testing the solution
def run_tests():
sol = Solution()
tests = [
([1,1,1,0,0,0,1,1,1,1,0], 2, 6),
([0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], 3, 10),
([1,1,1,1], 0, 4),
([0,0,0,1], 1, 2)
]
for i, (nums, k, expected) in enumerate(tests):
result = sol.longestOnes(nums, k)
print(f"Test {i+1}")
print("nums =", nums)
print("k =", k)
print("Expected =", expected)
print("Result =", result)
print("PASS" if result == expected else "FAIL")
print("-"*40)
if __name__ == "__main__":
run_tests()
# length of the last word
# reverse a string
# reverse vowels of the string
# reverse 2 digit of a numbere
# count digits
# sum of digits
# in memory replacement
# recursion problems