Window Sum

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 thesumof 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]

Solution:

Use ideas from subarray sum. maintain an array of the same size of sums, calculate and save current sums along the way. When the window size is big enough, minus previous sum to get the window sum.

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

results matching ""

    No results matching ""