Number of subarrays having sum exactly equal to k | Javascript program for the above approach ; Calculate all subarrays ; Calculate required sum ; Check if sum is equal to required sum
let arr = [ 10 , 2 , - 2 , - 20 , 10 ] ; let k = - 10 ; let n = arr . length ; let res = 0 ; for ( let i = 0 ; i < n ; i ++ ) { let sum = 0 ; for ( let j = i ; j < n ; j ++ ) { sum += arr [ j ] ; if ( sum == k ) res ++ ; } } document . write ( res ) ;