text: Count of subarrays having sum equal to its length | Set 2 | C # program for the above approach ; Function that counts the subarrays with sum of its elements as its length ; Store count of elements upto current element with length i ; Stores the readonly count of subarray ; Stores the prefix sum ; If size of subarray is 1 ; Iterate the array ; Find the sum ; Update frequency in map ; Print the total count ; Driver Code ; Given array [ ] arr ; Size of array ; Function Call
code: using System ; using System . Collections . Generic ; class GFG { static void countOfSubarray ( int [ ] arr , int N ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; int answer = 0 ; int sum = 0 ; mp [ 1 ] = 1 ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; if ( mp . ContainsKey ( sum - i ) ) answer += mp [ sum - i ] ; if ( mp . ContainsKey ( sum - 1 ) ) mp [ sum - 1 ] ++ ; else mp [ sum - 1 ] = 1 ; } Console . Write ( answer - 2 ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 0 , 2 , 1 , 2 , - 2 , 2 , 4 } ; int N = arr . Length ; countOfSubarray ( arr , N ) ; } }