Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Input: [2, 1, 5, 2, 3, 2], S=7
- Output: 2
- // Explanation: The smallest subarray with a sum great than or equal to '7' is [5, 2].
- Input: [2, 1, 5, 2, 8], S=7
- Output: 1
- // Explanation: The smallest subarray with a sum greater than or equal to '7' is [8].
- Input: [3, 4, 1, 1, 6], S=8
- Output: 3
- // Explanation: Smallest subarrays with a sum greater than or equal to '8' are [3, 4, 1] or [1, 1, 6].
- const smallest_subarray_with_given_sum = function(s, arr) {
- if (arr.length === 0) {
- return -1;
- }
- let size = 0;
- let min = Number.MAX_SAFE_INTEGER;
- let sum = 0;
- let left = 0
- for (let right = 0; right < arr.length; right++) {
- sum += arr[right];
- size++;
- if (sum >= s) {
- min = Math.min(min, size);
- sum -= arr[left++];
- size--;
- }
- }
- return min;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement