Count of elements which is the sum of a subarray of the given Array | C ++ implementation to count the elements such that their exist a subarray whose sum is equal to this element ; Function to count the elements such that their exist a subarray whose sum is equal to this element ; Loop to count the frequency ; Loop to iterate over every possible subarray of the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countElement ( int arr [ ] , int n ) { map < int , int > freq ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { freq [ arr [ i ] ] ++ ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { int tmpsum = arr [ i ] ; for ( int j = i + 1 ; j < n ; j ++ ) { tmpsum += arr [ j ] ; if ( freq . find ( tmpsum ) != freq . end ( ) ) { ans += freq [ tmpsum ] ; } } } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countElement ( arr , n ) << endl ; return 0 ; }