Skip to content

Commit 07b6e6c

Browse files
committed
solved a simple and intutive dsa problem using concept of sliding window
1 parent 00e9d86 commit 07b6e6c

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
Given an array of both positive and negative integers, the task is to compute sum of minimum and maximum elements of all sub-array of size k.
3+
4+
https://www.geeksforgeeks.org/sum-minimum-maximum-elements-subarrays-size-k/
5+
"""
6+
7+
#this function will return sum of min and max of the window
8+
def get_min_max(array:list ,start:int ,end:int) -> int:
9+
10+
max = min = array[start]
11+
12+
for i in range(start+1,end+1):
13+
if array[i] < min:
14+
min = array[i]
15+
if array[i] > max:
16+
max = array[i]
17+
18+
return max+min
19+
20+
def sum(array:list ,size:int ,k:int) -> int:
21+
"""
22+
Args:
23+
array (list): the input array
24+
size (int): size of the array
25+
k (int): size of the sub-array
26+
27+
Returns:
28+
int : sum of the minimum and maximum elements of all sub-arrays of size-k
29+
"""
30+
31+
# create first window of size k
32+
start ,end = 0 ,k-1
33+
result = 0
34+
#get the minimum and maximum element from the window and add it to the result
35+
result += get_min_max(array,size,start,end)
36+
37+
38+
while start < size-k and end < size:
39+
start += 1
40+
end += 1
41+
result += get_min_max(array,start,end)
42+
43+
return result
44+
45+
if __name__ == '__main__':
46+
array = [2, 5, -1, 7, -3, -1, -2]
47+
K = 4
48+
size = 7
49+
print(sum(array,size,K))

0 commit comments

Comments
 (0)