Count array elements that can be represented as sum of at least two consecutive array elements | Java 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
import java . util . * ; class GFG { static int countElements ( int [ ] a , int n ) { int [ ] cnt = new int [ n + 1 ] ; int ans = 0 ; for ( int k : a ) { ++ cnt [ k ] ; } 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 ; } public static void main ( String [ ] args ) { int [ ] a = { 1 , 1 , 1 , 1 , 1 } ; System . out . println ( countElements ( a , a . length ) ) ; } }