Problem
Given an array of n integer, and a moving window(size k), move the window at each iteration from the start of the array,
find the sum of the element inside the window at each moving.
Example
For array [1,2,7,8,5], moving window size k = 3.
1 + 2 + 7 = 10
2 + 7 + 8 = 17
7 + 8 + 5 = 20
return [10,17,20]
思路
- questions
- nums could be null?
- k could be <= 0? or >=nums.length

public int[] winSum(int[] nums, int k) {
if (nums == null || nums.length == 0 || k <= 0) {
return new int[0];
}
int n = nums.length;
int[] ans = new int[n - k + 1];
int[] ps = new int[k + 1];
for (int i = 1; i <= n; i++) {
ps[i] = ps[i - 1] + nums[i - 1];
if (i >= k) {
ans[i - k] = ps[i] - ps[i - k];
}
}
return ans;
}