All submissions

Sliding Window Sum

Code

#include <stdio.h>

void sliding_window_sum(int a[], int n, int k) 
{
    int i;
    for(i=0;i<n-k+1;i++) //if k=3, we can reach till n-3 only because, then only we can access next two more elemnents for accessing 3 elements in a row.
    {
        int temp=0;
        int ans=0;
        while(temp<k) //running loop k times, to find each window sum.
        {
            ans=ans+a[i+temp]; //a[i+temp] is the key point in finding sum of each window.
            temp++;
        }
        printf("%d ",ans);
    }
}

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

 

 

 

Loading...

Input

5 3 1 2 3 4 5

Expected Output

6 9 12