604 · Window Sum - LintCode

# Description

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

Example 1

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

# Solution

public class Solution {
    /**
     * @param nums: a list of integers.
     * @param k: length of window.
     * @return: the sum of the element inside the window at each moving.
     */
    public int[] winSum(int[] nums, int k) {
       if (k == 0) return new int[] {};
       int left = 0, right = k - 1, sum = 0;
       //window sum
       for (int i = 0; i < k; i++){
           sum += nums[i];
       }
       int[] res = new int[nums.length - k + 1];
       int index = 0;
        System.out.println("sum "+ sum);
       res[index++] = sum;  // 讓之後的 index 為 1
       
       System.out.println("res[] "+ res[0]);
       while (right < nums.length - 1){
           sum -= nums[left]; //10 減去 1 [(1,) 2,7,4]
           left++; // 窗口向右移
           right++; 
           sum += nums[right]; //9 加上 4
           res[index++] = sum; 
       }
       return res;
    }
}