Complete the code to calculate the sum of the first window of size k in the array.
function initialWindowSum(arr: number[], k: number): number {
let sum = 0;
for (let i = 0; i < [1]; i++) {
sum += arr[i];
}
return sum;
}The loop should run from 0 to k-1 to sum the first k elements.
Complete the code to slide the window by one position and update the sum.
function slideWindowSum(arr: number[], start: number, end: number, currentSum: number): number {
return currentSum - arr[[1]] + arr[end];
}When sliding the window, subtract the element leaving the window at index start.
Fix the error in the code to correctly find the maximum sum of any window of size k.
function maxWindowSum(arr: number[], k: number): number {
let maxSum = 0;
let windowSum = 0;
for (let i = 0; i < k; i++) {
windowSum += arr[i];
}
maxSum = windowSum;
for (let i = k; i < arr.length; i++) {
windowSum = windowSum - arr[i - k] + arr[[1]];
if (windowSum > maxSum) {
maxSum = windowSum;
}
}
return maxSum;
}The new element entering the window is at index i.
Fill both blanks to create a function that returns an array of sums of all windows of size k.
function allWindowSums(arr: number[], k: number): number[] {
const result: number[] = [];
let windowSum = 0;
for (let i = 0; i < [1]; i++) {
windowSum += arr[i];
}
result.push(windowSum);
for (let i = k; i < arr.length; i++) {
windowSum = windowSum - arr[i - [2]] + arr[i];
result.push(windowSum);
}
return result;
}The first loop sums the first k elements. The sliding window subtracts the element leaving at i-k.
Fill all three blanks to implement a function that finds the minimum sum of any window of size k.
function minWindowSum(arr: number[], k: number): number {
let minSum = 0;
let windowSum = 0;
for (let i = 0; i < [1]; i++) {
windowSum += arr[i];
}
minSum = windowSum;
for (let i = [2]; i < arr.length; i++) {
windowSum = windowSum - arr[i - k] + arr[[3]];
if (windowSum < minSum) {
minSum = windowSum;
}
}
return minSum;
}Sum the first k elements, start sliding from index k, and add the element at i when sliding.
