[lintcode] problem 604 – window sum

Given an array of n integers, 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

Input:array = [1,2,7,8,5], k = 3

Output:[10,17,20]

Explanation:
1 + 2 + 7 = 10
2 + 7 + 8 = 17
7 + 8 + 5 = 20

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public int[] winSum(int[] nums, int k) {
if (nums == null || k <= 0 || nums.length < k)
return new int[0];

int n = nums.length;
int[] result = new int[n-k+1];
int sum = 0;

for (int i = 0; i < k; i++)
result[0] += nums[i];

for (int i = 1; i < n - k + 1; i++)
result[i] = result[i-1] - nums[i-1] + nums[i+k-1];

return result;
}