Count array elements exceeding sum of preceding K elements | Java program for the above approach ; Function to count array elements exceeding sum of preceding K elements ; Iterate over the array ; Update prefix sum ; Check if arr [ K ] > arr [ 0 ] + . . + arr [ K - 1 ] ; Increment count ; Check if arr [ i ] > arr [ i - K - 1 ] + . . + arr [ i - 1 ] ; Increment count ; Driver Code ; Given array
class GFG { static int countPrecedingK ( int a [ ] , int n , int K ) { int [ ] prefix = new int [ n ] ; prefix [ 0 ] = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { prefix [ i ] = prefix [ i - 1 ] + a [ i ] ; } int ctr = 0 ; if ( prefix [ K - 1 ] < a [ K ] ) ctr ++ ; for ( int i = K + 1 ; i < n ; i ++ ) { if ( prefix [ i - 1 ] - prefix [ i - K - 1 ] < a [ i ] ) ctr ++ ; } return ctr ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 8 , 10 , - 2 , 7 , 5 , 5 , 9 , 15 } ; int N = arr . length ; int K = 2 ; System . out . print ( countPrecedingK ( arr , N , K ) ) ; } }