Count of subarrays with sum at least K | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int k_sum ( int a [ ] , int n , int k ) { int r = 0 , sum = 0 ; int ans = 0 ; for ( int 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 ; } int main ( ) { int a [ ] = { 6 , 1 , 2 , 7 } , k = 10 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << k_sum ( a , n , k ) ; return 0 ; }