Imagine you have a row of numbers, and you want to look at them through a small window that is exactly k numbers wide. As you slide that window from the left end to the right end, each position shows you a group of k neighbors sitting next to each other. The task is to add up the numbers in each window and find the smallest total you can get.
A subarray is just a chunk of the array made of elements that are next to each other (no gaps, no reordering). A subarray "of size k" simply means a chunk that contains exactly k numbers.
You are given:
arrkYour job is to look at every possible group of k neighbors, add each group, and return the minimum sum. If the array is too short to even form one group of size k, there is no valid answer, so you return -1.
Input: arr = [4, 4, 5, 6, 4], k = 3
Slide a window of size 3 across the array:
[4, 4, 5] → sum is 4 + 4 + 5 = 13[4, 5, 6] → sum is 4 + 5 + 6 = 15[5, 6, 4] → sum is 5 + 6 + 4 = 15The smallest of these sums is 13, so the output is 13.
Input: arr = [1, 2, 3, 5], k = 1
When k = 1, each window holds just one number. So the windows are [1], [2], [3], [5]. The smallest single number is 1, so the output is 1.
The slow idea would be: for every starting position, add up the next k numbers from scratch. That works, but it repeats a lot of addition.
A smarter trick is the sliding window. Notice that when the window moves one step to the right, it only loses one number on the left and gains one number on the right. So instead of re-adding everything, you can:
k numbers to get the first window sum. Call this your current sum and also your best (minimum) sum so far.If k is larger than the number of elements in arr, you can never build a window of size k. In that case, return -1.