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
< ? php function findMinAvgSubarray ( $ arr , $ n , $ k ) { if ( $ n < $ k ) return ; $ res_index = 0 ; $ curr_sum = 0 ; for ( $ i = 0 ; $ i < $ k ; $ i ++ ) $ curr_sum += $ arr [ $ i ] ; $ min_sum = $ curr_sum ; for ( $ 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 ) ; } } echo " Subarray between [ " ▁ , $ res _ index ▁ , ▁ " , " ▁ , $ res _ index ▁ + ▁ $ k ▁ - ▁ 1 , ▁ " ] has minimum average " ; } $ arr = array ( 3 , 7 , 90 , 20 , 10 , 50 , 40 ) ; $ k = 3 ; $ n = sizeof ( $ arr ) / sizeof ( $ arr [ 0 ] ) ; findMinAvgSubarray ( $ arr , $ n , $ k ) ; return 0 ; ? >