Count array elements exceeding sum of preceding K elements | 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 ; Given array
function countPrecedingK ( a , n , K ) { let prefix = new Array ( n ) . fill ( 0 ) ; prefix [ 0 ] = a [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { prefix [ i ] = prefix [ i - 1 ] + a [ i ] ; } let ctr = 0 ; if ( prefix [ K - 1 ] < a [ K ] ) ctr ++ ; for ( let i = K + 1 ; i < n ; i ++ ) { if ( prefix [ i - 1 ] - prefix [ i - K - 1 ] < a [ i ] ) ctr ++ ; } return ctr ; } let arr = [ 2 , 3 , 8 , 10 , - 2 , 7 , 5 , 5 , 9 , 15 ] ; let N = arr . length ; let K = 2 ; document . write ( countPrecedingK ( arr , N , K ) ) ;