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 ; Driver Code ; Given array
def countPrecedingK ( a , n , K ) : NEW_LINE INDENT prefix = [ 0 ] * n NEW_LINE prefix [ 0 ] = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + a [ i ] NEW_LINE DEDENT ctr = 0 NEW_LINE if ( prefix [ K - 1 ] < a [ K ] ) : NEW_LINE INDENT ctr += 1 NEW_LINE DEDENT for i in range ( K + 1 , n ) : NEW_LINE INDENT if ( prefix [ i - 1 ] - prefix [ i - K - 1 ] < a [ i ] ) : NEW_LINE INDENT ctr += 1 NEW_LINE DEDENT DEDENT return ctr NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 8 , 10 , - 2 , 7 , 5 , 5 , 9 , 15 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( countPrecedingK ( arr , N , K ) ) NEW_LINE DEDENT