Number of subarrays having sum exactly equal to k | C # program to find number of subarrays with sum exactly equal to k . ; Function to find number of subarrays with sum exactly equal to k . ; HashMap to store number of subarrays starting from index zero having particular value of sum . ; Sum of elements so far ; Add current element to sum so far . ; If currsum is equal to desired sum , then a new subarray is found . So increase count of subarrays . ; currsum exceeds given sum by currsum - sum . Find number of subarrays having this sum and exclude those subarrays from currsum by increasing count by same amount . ; Add currsum value to count of different values of sum . ; Driver Code
using System ; using System . Collections . Generic ; class GFG { public static int findSubarraySum ( int [ ] arr , int n , int sum ) { Dictionary < int , int > prevSum = new Dictionary < int , int > ( ) ; int res = 0 ; int currsum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { currsum += arr [ i ] ; if ( currsum == sum ) res ++ ; if ( prevSum . ContainsKey ( currsum - sum ) ) res += prevSum [ currsum - sum ] ; if ( ! prevSum . ContainsKey ( currsum ) ) prevSum . Add ( currsum , 1 ) ; else { int count = prevSum [ currsum ] ; prevSum [ currsum ] = count + 1 ; } } return res ; } public static void Main ( ) { int [ ] arr = { 10 , 2 , - 2 , - 20 , 10 } ; int sum = - 10 ; int n = arr . Length ; Console . Write ( findSubarraySum ( arr , n , sum ) ) ; } }