Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. Input: [2, 1, 5, 2, 3, 2], S=7
  2. Output: 2
  3. // Explanation: The smallest subarray with a sum great than or equal to '7' is [5, 2].
  4.  
  5. Input: [2, 1, 5, 2, 8], S=7
  6. Output: 1
  7. // Explanation: The smallest subarray with a sum greater than or equal to '7' is [8].
  8.  
  9. Input: [3, 4, 1, 1, 6], S=8
  10. Output: 3
  11. // Explanation: Smallest subarrays with a sum greater than or equal to '8' are [3, 4, 1] or [1, 1, 6].
  12.  
  13. const smallest_subarray_with_given_sum = function(s, arr) {
  14. if (arr.length === 0) {
  15. return -1;
  16. }
  17. let size = 0;
  18. let min = Number.MAX_SAFE_INTEGER;
  19. let sum = 0;
  20. let left = 0
  21. for (let right = 0; right < arr.length; right++) {
  22. sum += arr[right];
  23. size++;
  24. if (sum >= s) {
  25. min = Math.min(min, size);
  26. sum -= arr[left++];
  27. size--;
  28. }
  29. }
  30. return min;
  31. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement