forked from Algo-Phantoms/Algo-Tree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SlidingWindowMax.py
62 lines (43 loc) · 1010 Bytes
/
SlidingWindowMax.py
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
'''
Description:
Given an array of N elements and a value K (K <= N) , calculate maximum summation
of K consecutive elements in the array.
'''
# Python Code:
# number of entries in array
n=int(input())
# number of consecutive elements
k=int(input())
# Whole array input
lst = list(map(int,input().strip().split()))[:n]
sum=0
if(n==k):
for i in range(0,n):
sum+= lst[i]
print (sum)
if(n>k): # calculate sum of first window of size K
mxsum=0
wnsum=0
for i in range(0,k):
mxsum+= lst[i]
wnsum=mxsum # calculate sum of remaining windows
for i in range(k,n):
wnsum+=(lst[i]-lst[i-k])
if(wnsum>mxsum):
mxsum=wnsum
print (mxsum)
'''
Test Cases Standard I/O
1. if N == K
N= 5
K= 5
lst= { 1 2 3 4 5 }
Output : 15
2. if N > K
N= 5
K= 3
lst= { 5 2 -1 0 3 }
Output : 6
Time Complexity : O(N) # here N= number of entries in the array
Space Complexity : O(1)
'''