Skip to content
LC-2302 Hard LeetCode

2302. Count Subarrays With Score Less Than K

Read the full problem statement on LeetCode.
Difficulty: hard Acceptance: 62% Topics: Array, Binary Search, Sliding Window, Prefix Sum
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(1)

# sliding window, two pointers
class Solution(object):
    def countSubarrays(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        result = total = left = 0
        for right in xrange(len(nums)):
            total += nums[right]
            while total*(right-left+1) >= k:
                total -= nums[left]
                left += 1
            result += right-left+1
        return result

Solution from kamyu104/LeetCode-Solutions · MIT