Advertisement
Guest User

Untitled

a guest
May 25th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.57 KB | None | 0 0
  1. const max_sub_array_of_size_k = function(k, arr) {
  2. // The time complexity of the above algorithm will be O(N*K)
  3. let maxSum = 0;
  4. let windowSum = 0;
  5. for (let i = 0, len = arr.length; i < len-k; i++) {
  6. windowSum = 0;
  7. for (let j = i; j < i + k; j++) {
  8. windowSum += arr[j]
  9. }
  10. maxSum = Math.max(maxSum, windowSum);
  11. }
  12. return maxSum;
  13. };
  14.  
  15.  
  16. console.log(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}`)
  17. console.log(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])}`)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement