Find the subarray with least average | Prints beginning and ending indexes of subarray of size k with minimum average ; k must be smaller than or equal to n ; Initialize beginning index of result ; Compute sum of first subarray of size k ; Initialize minimum sum as current sum ; Traverse from ( k + 1 ) ' th ▁ ▁ element ▁ to ▁ n ' th element ; Add current item and remove first item of previous subarray ; Update result if needed ; Driver Code ; Subarray size
def findMinAvgSubarray ( arr , n , k ) : NEW_LINE INDENT if ( n < k ) : return 0 NEW_LINE res_index = 0 NEW_LINE curr_sum = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT curr_sum += arr [ i ] NEW_LINE DEDENT min_sum = curr_sum NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT curr_sum += arr [ i ] - arr [ i - k ] NEW_LINE if ( curr_sum < min_sum ) : NEW_LINE INDENT min_sum = curr_sum NEW_LINE res_index = ( i - k + 1 ) NEW_LINE DEDENT DEDENT print ( " Subarray ▁ between ▁ [ " , res_index , " , ▁ " , ( res_index + k - 1 ) , " ] ▁ has ▁ minimum ▁ average " ) NEW_LINE DEDENT arr = [ 3 , 7 , 90 , 20 , 10 , 50 , 40 ] NEW_LINE k = 3 NEW_LINE n = len ( arr ) NEW_LINE findMinAvgSubarray ( arr , n , k ) NEW_LINE