Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const max_sub_array_of_size_k = function(k, arr) {
- // The time complexity of the above algorithm will be O(N*K)
- let maxSum = 0;
- let windowSum = 0;
- for (let i = 0, len = arr.length; i < len-k; i++) {
- windowSum = 0;
- for (let j = i; j < i + k; j++) {
- windowSum += arr[j]
- }
- maxSum = Math.max(maxSum, windowSum);
- }
- return maxSum;
- };
- console.log(`Maximum sum of a subarray of size K: ${max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])}`)
- 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