Count array elements that can be represented as sum of at least two consecutive array elements | C ++ program for above approach ; Function to find the number of array elements that can be represented as the sum of two or more consecutive array elements ; Stores the frequencies of array elements ; Stores required count ; Update frequency of each array element ; Find sum of all subarrays ; Increment ans by cnt [ sum ] ; Reset cnt [ sum ] by 0 ; Return ans ; Driver Code ; Given array ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countElements ( int a [ ] , int n ) { int cnt [ n + 1 ] = { 0 } ; memset ( cnt , 0 , sizeof ( cnt ) ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ++ cnt [ a [ i ] ] ; } for ( int l = 0 ; l < n ; ++ l ) { int sum = 0 ; for ( int r = l ; r < n ; ++ r ) { sum += a [ r ] ; if ( l == r ) continue ; if ( sum <= n ) { ans += cnt [ sum ] ; cnt [ sum ] = 0 ; } } } return ans ; } int main ( ) { int a [ ] = { 1 , 1 , 1 , 1 , 1 } ; int N = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countElements ( a , N ) ; }