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
def k_sum ( a , n , k ) : NEW_LINE INDENT r , sum = 0 , 0 ; NEW_LINE ans = 0 ; NEW_LINE for l in range ( n ) : NEW_LINE INDENT while ( sum < k ) : NEW_LINE INDENT if ( r == n ) : NEW_LINE INDENT break ; NEW_LINE DEDENT else : NEW_LINE INDENT sum += a [ r ] ; NEW_LINE r += 1 ; NEW_LINE DEDENT DEDENT if ( sum < k ) : NEW_LINE INDENT break ; NEW_LINE DEDENT ans += n - r + 1 ; NEW_LINE sum -= a [ l ] ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT a = [ 6 , 1 , 2 , 7 ] ; k = 10 ; NEW_LINE n = len ( a ) ; NEW_LINE print ( k_sum ( a , n , k ) ) ; NEW_LINE