Subarray Sum Less Than K (IB)

Sliding Window

Problem

Your are given an array of positive integers nums.

Count and print the number of (contiguous) subarrays where the sum of all the elements in the subarray is less than k.

For example:

 Input: nums = [2, 5, 6], k = 10
 Output: 4

Solution

class Solution:
    def solve(self, nums, k):
        start = 0
        sums = 0
        count = 0
        
        for i in range(len(nums)):
            sums+=nums[i]
            while sums >= k:
                sums-=nums[start]
                start+=1
            count+=i-start+1
        return count
        
#Time: O(n)
#Space: O(n)

Last updated