Sliding Window Sum

Code

#include <stdio.h>

void sliding_window_sum(int arr[], int n, int k) {
    // Your logic here
    volatile int inital_sum = 0;
    volatile int i;
    
    for(i=0;i<k;i++){
        inital_sum += arr[i];
    }
    printf("%d ", inital_sum);

    for(i=k;i<n;i++){
        inital_sum += arr[i]; //add new element to the window
        inital_sum -= arr[i-k];
        printf("%d", inital_sum);

        if(i<n-1){
            printf(" ");
        }
    }    
}

int main() {
    int n, k, arr[100];
    scanf("%d %d", &n, &k);
    for (int i = 0; i < n; i++) scanf("%d", &arr[i]);

    sliding_window_sum(arr, n, k);
    return 0;
}

Solving Approach

Get initial window sum, print this sum along with a space

Start another loop from end of initial slide window

  • add the new element to the array by increasing the window size towards the right

  • subtract the first element of the past window, or the left most element of window

  • print the value

  • if not the last element of array being indexed, print a space

 

 

Upvote
Downvote
Loading...

Input

5 3 1 2 3 4 5

Expected Output

6 9 12