Count array elements exceeding sum of preceding K elements | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPrecedingK ( int a [ ] , int n , int K ) { int prefix [ 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 ; } int main ( ) { int arr [ ] = { 2 , 3 , 8 , 10 , -2 , 7 , 5 , 5 , 9 , 15 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << countPrecedingK ( arr , N , K ) ; return 0 ; }