Non-Leetcode Questions: Sliding Window Sum
Given a list of integers and a window size, return a new list of integers where each integer is the sum of all integers in the kth window of the input list. The kth window of the input list is the integers from index k to index k + window size - 1(inclusive).
public int[] slidingWindowSum(int num[], int window_size){
// initialize result
int sums[] = new int[Math.max(num.length-window_size+1,1)];
// check if window_size is greater than num[] size, return -1
if(window_size > num.length) sums[0] = -1;
// current sum, function as a window
int cur_sum = 0;
// go through num[]
for(int i = 0, j = 0;i < num.length;i++){
// each time a new number come, add to window
cur_sum += num[i];
if(i >= window_size-1){
// if not the start window, delete the first one from window
if(i-window_size >= 0) cur_sum -= num[i-window_size];
// set window(cur_sum) to output
sums[j++] = cur_sum;
}
}
return sums;
}
Read full article from Non-Leetcode Questions: Sliding Window Sum
Given a list of integers and a window size, return a new list of integers where each integer is the sum of all integers in the kth window of the input list. The kth window of the input list is the integers from index k to index k + window size - 1(inclusive).
public int[] slidingWindowSum(int num[], int window_size){
// initialize result
int sums[] = new int[Math.max(num.length-window_size+1,1)];
// check if window_size is greater than num[] size, return -1
if(window_size > num.length) sums[0] = -1;
// current sum, function as a window
int cur_sum = 0;
// go through num[]
for(int i = 0, j = 0;i < num.length;i++){
// each time a new number come, add to window
cur_sum += num[i];
if(i >= window_size-1){
// if not the start window, delete the first one from window
if(i-window_size >= 0) cur_sum -= num[i-window_size];
// set window(cur_sum) to output
sums[j++] = cur_sum;
}
}
return sums;
}
Read full article from Non-Leetcode Questions: Sliding Window Sum