Difference between maximum and minimum average of all K | C ++ program for the above approach ; Function to find the difference between the maximum and minimum subarrays of length K ; Stores the sum of subarray over the range [ 0 , K ] ; Iterate over the range [ 0 , K ] ; Store min and max sum ; Iterate over the range [ K , N - K ] ; Increment sum by arr [ i ] - arr [ i - K ] ; Update max and min moving sum ; Return difference between max and min average ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; double Avgdifference ( double arr [ ] , int N , int K ) { double sum = 0 ; for ( int i = 0 ; i < K ; i ++ ) sum += arr [ i ] ; double min = sum ; double max = sum ; for ( int i = K ; i <= N - K + 1 ; i ++ ) { sum += arr [ i ] - arr [ i - K ] ; if ( min > sum ) min = sum ; if ( max < sum ) max = sum ; } return ( max - min ) / K ; } int main ( ) { double arr [ ] = { 3 , 8 , 9 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << Avgdifference ( arr , N , K ) ; return 0 ; }