Count of subarrays with sum at least K | Function to return the number of subarrays with sum atleast k ; To store the right index and the current sum ; To store the number of sub - arrays ; For all left indexes ; Get elements till current sum is less than k ; No such subarray is possible ; Add all possible subarrays ; Remove the left most element ; Return the required answer ; Driver code
function k_sum ( a , n , k ) { let r = 0 , sum = 0 ; let ans = 0 ; for ( let l = 0 ; l < n ; l ++ ) { while ( sum < k ) { if ( r == n ) break ; else { sum += a [ r ] ; r ++ ; } } if ( sum < k ) break ; ans += n - r + 1 ; sum -= a [ l ] ; } return ans ; } let a = [ 6 , 1 , 2 , 7 ] , k = 10 ; let n = a . length ; document . write ( k_sum ( a , n , k ) ) ;