Difference between maximum and minimum average of all K | Java implementation of the above approach ; Function to find the difference between averages of the maximum and the minimum subarrays of length k ; Stores min and max sum ; Iterate through starting points ; Sum up next K elements ; Update max and min moving sum ; Return the difference between max and min average ; Driver Code ; Given Input ; Function Call
import java . io . * ; class GFG { static double Avgdifference ( double arr [ ] , int N , int K ) { double min = 1000000 , max = - 1 ; for ( int i = 0 ; i <= N - K ; i ++ ) { double sum = 0 ; for ( int j = 0 ; j < K ; j ++ ) { sum += arr [ i + j ] ; } if ( min > sum ) min = sum ; if ( max < sum ) max = sum ; } return ( max - min ) / K ; } public static void main ( String [ ] args ) { double arr [ ] = { 3 , 8 , 9 , 15 } ; int N = arr . length ; int K = 2 ; System . out . println ( Avgdifference ( arr , N , K ) ) ; } }