Sliding Window Sum

Code

#include <stdio.h>

void sliding_window_sum(int arr[], int n, int k) {
    // Your logic here
     if (n < k) {
        printf("Invalid input: Array size is smaller than k.\n");
        return;
    }

    // 1. Calculate the sum of the first window (first k elements)
    int window_sum = 0;
    for (int i = 0; i < k; i++) {
        window_sum += arr[i];
    }

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

    // 2. Slide the window from the k-th element to the end
    for (int i = k; i < n; i++) {
        // Update the window sum for the next window
        // Subtract the element leaving the window from the left (arr[i - k])
        // Add the new element entering the window from the right (arr[i])
        window_sum += arr[i] - arr[i - k];

        // Print the sum of the current window
        printf("%d ", window_sum);
    }
    printf("\n");
}

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