Given an array of integers nums and an integer k, return an array of sums of every contiguous subarray of size k.
You must use a sliding window approach to calculate the sums efficiently. The result should contain n - k + 1 elements, where n is the length of nums. The i-th element of the result (0-based) is the sum of nums[i..i+k-1].
Function Signature
def subarray_sums(nums: list[int], k: int) -> list[int]:
Constraints
-
1 <= nums.length <= 10^5
-
-10^4 <= nums[i] <= 10^4
-
1 <= k <= nums.length
Examples
Input: nums = [1,2,3,4,5], k = 3
Output: [6,9,12]
The subarrays of size 3 are [1,2,3], [2,3,4] and [3,4,5], with sums 6, 9 and 12.
Input: nums = [2,-1,5,3,-2,4], k = 2
Output: [1,4,8,1,2]
The subarrays of size 2 are [2,-1], [-1,5], [5,3], [3,-2] and [-2,4], with sums 1, 4, 8, 1 and 2.
Input: nums = [7,-3,2], k = 3
Output: [6]
When k equals the array length there is exactly n - k + 1 = 1 window, the whole array, and its sum is 7 + (-3) + 2 = 6.