Find the subarray with least average | A Simple C ++ program to find minimum average subarray ; 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 program ; Subarray size
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinAvgSubarray ( int arr [ ] , int n , int k ) { if ( n < k ) return ; int res_index = 0 ; int curr_sum = 0 ; for ( int i = 0 ; i < k ; i ++ ) curr_sum += arr [ i ] ; int min_sum = curr_sum ; for ( int i = k ; i < n ; i ++ ) { curr_sum += arr [ i ] - arr [ i - k ] ; if ( curr_sum < min_sum ) { min_sum = curr_sum ; res_index = ( i - k + 1 ) ; } } cout << " Subarray ▁ between ▁ [ " << res_index << " , ▁ " << res_index + k - 1 << " ] ▁ has ▁ minimum ▁ average " ; } int main ( ) { int arr [ ] = { 3 , 7 , 90 , 20 , 10 , 50 , 40 } ; int k = 3 ; int n = sizeof arr / sizeof arr [ 0 ] ; findMinAvgSubarray ( arr , n , k ) ; return 0 ; }