[Don't comment your code here - You will be immediately disqualified]
Given an array of positive numbers and a positive number ‘k,’ find the maximum sum of any contiguous subarray of size ‘k’.
Example 1:
Input: [2, 1, 5, 1, 3, 2], k=3 Output: 9 Explanation: Subarray with maximum sum is [5, 1, 3].
Example 2:
Input: [2, 3, 4, 1, 5], k=2 Output: 7 Explanation: Subarray with maximum sum is [3, 4].
function maxSum(arr, k) {
let sum=0, res=Number.NEGATIVE_INFINITY;
for(let i=0; i<k; i++) {
sum+=arr[i];
}
res=sum;
for(let i=1; i+k<=arr.length; i++) {
sum-=arr[i-1];
sum+=arr[i+k-1];
res = Math.max(res, sum);
}
return res;
}
console.log(maxSum([2, 3, 4, 1, 5], 3));