![]() |
VOOZH | about |
Given an array arr[] of non-negative numbers and a non-negative number k, find the number of subarrays having sum less than k. We may assume that there is no overflow.
Examples :
Input: arr[] = [2, 5, 6], K = 10
Output: 4
Explanation: The subarrays are [2], [5], [6], and [2, 5]Input: arr[] = [1, 11, 2, 3, 15], K = 10
Output: 4
Explanation: The subarrays are [1], [2], [3], and [2, 3]
Check every possible subarray and compute its sum. For each starting index, extend the subarray one element at a time and count it if the sum is less than K. Stop extending when the sum becomes greater than or equal to K since it will only increase further.
Steps:
4
The idea of this approach is to use two pointers, start and end, to form a window (subarray). This window expands when we move end forward and shrinks when we move start forward, so that the sum of elements inside the window always remains less than K.
Steps
4