Sum of all subarrays of size K | Function to find the sum of all subarrays of size K ; Initialize sum = 0 ; Consider first subarray of size k Store the sum of elements ; Print the current sum ; Consider every subarray of size k Remove first element and add current element to the window ; Add the element which enters into the window and subtract the element which pops out from the window of the size K ; Print the sum of subarray ; Drivers Code ; Function Call
def calcSum ( arr , n , k ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT print ( sum , end = " ▁ " ) NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT sum = ( sum - arr [ i - k ] ) + arr [ i ] NEW_LINE print ( sum , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE calcSum ( arr , n , k ) NEW_LINE DEDENT