Skip to content

Commit 2766a43

Browse files
committed
sliding window variable
1 parent 3bd565a commit 2766a43

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

arrays/slidingwindowvariable.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# find the length of the longest subarray, with the same value in each position
2+
def longestSubarray(arr: list[int]) -> int:
3+
l = maxLen = 0
4+
for r in range(0, len(arr)):
5+
if arr[l] != arr[r]:
6+
l = r
7+
maxLen = max(maxLen, r - l + 1)
8+
return maxLen
9+
10+
# find the min length sub array where the sum is >= target. All values are positive
11+
def minSubarray(arr: list[int], target: int) -> int:
12+
l, currSum, minLen = 0, 0, float("inf")
13+
for r in range(0, len(arr)):
14+
currSum += arr[r]
15+
while currSum >= target:
16+
minLen = min(minLen, r - l + 1)
17+
currSum -= arr[l]
18+
l += 1
19+
20+
return 0 if minLen == float("inf") else minLen
21+
22+
print(longestSubarray([1,2,3,3,3,6,3,8])) # 3
23+
print(longestSubarray([1,2,3,4,5,6,7,8])) # 1
24+
25+
print(minSubarray([1,2,3,3,3,6,3,8], 3)) # 1
26+
print(minSubarray([1], 10)) # 0
27+
28+

0 commit comments

Comments
 (0)