Count array elements that can be represented as sum of at least two consecutive array elements | 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 ; Given array ; Function call
function countElements ( a , n ) { var cnt = Array ( n + 1 ) . fill ( 0 ) ; var ans = 0 ; for ( k = 0 ; k < n ; k ++ ) { cnt [ a [ k ] ] ++ ; } for ( l = 0 ; l < n ; ++ l ) { var sum = 0 ; for ( r = l ; r < n ; ++ r ) { sum += a [ r ] ; if ( l == r ) continue ; if ( sum <= n ) { ans += cnt [ sum ] ; cnt [ sum ] = 0 ; } } } return ans ; } var a = [ 1 , 1 , 1 , 1 , 1 ] ; document . write ( countElements ( a , a . length ) ) ;