Code

#include <stdio.h>

void sliding_window_sum(int arr[], int n, int k) {
    if (k > n || k <= 0) return; // Invalid window size

    int window_sum = 0;

    // Compute sum of first window
    for (int i = 0; i < k; i++) {
        window_sum += arr[i];
    }

    // Print the first window sum
    printf("%d ", window_sum);

    // Slide the window across the array
    for (int i = k; i < n; i++) {
        window_sum += arr[i] - arr[i - k]; // Add new element, remove old
        printf("%d ", window_sum);
    }

    printf("\n"); // End the output line
}

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

 

 

 

Upvote
Downvote
Loading...

Input

5 3 1 2 3 4 5

Expected Output

6 9 12