Sliding Window Maximum by Heap Sorting 2025 (Required)

Time limit: 5000ms
Memory limit: 256mb

Description:
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

Return the max sliding window.

The main function has been provided. You need to complete three functions.

Sample Input 1:
3
8
1 3 -1 -3 5 3 6 7

Sample Output 1:

Enter the window size:
Enter the size of the array:
Enter the elements of the array:
3 3 5 5 6 7

Explanation: 
Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7


Sample Input 2:

1
1
1

Sample Output 2:
Enter the window size:
Enter the size of the array:
Enter the elements of the array:
1


Code Template:

#include <stdio.h>
#include <stdlib.h>

// Function to maintain the max-heap property
void maxHeapify(int* arr, int size, int i) {
    /*
        Fill in your code here.
    */
}

// Function to build a max-heap from an array
void buildMaxHeap(int* arr, int size) {
    /*
        Fill in your code here.
    */
}

// Function to find the maximum value in each sliding window
int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize) {
    if (nums == NULL || numsSize == 0 || k == 0) {
        *returnSize = 0;
        return NULL;
    }

    *returnSize = numsSize - k + 1;
    int* result = (int*)malloc(*returnSize * sizeof(int));

    /*
        Fill in your code here.
    */

    return result;
}

int main() {
    int k, numsSize;
    int* nums;

    printf("Enter the window size:\n");
    scanf("%d", &k);

    printf("Enter the size of the array:\n");
    scanf("%d", &numsSize);

    nums = (int*)malloc(numsSize * sizeof(int));
    printf("Enter the elements of the array:\n");
    for (int i = 0; i < numsSize; i++) {
        scanf("%d", &nums[i]);
    }

    int returnSize;
    int* result = maxSlidingWindow(nums, numsSize, k, &returnSize);

    // Print the result
    for (int i = 0; i < returnSize; i++) {
        printf("%d", result[i]);
        if (i < returnSize - 1) {
            printf(" ");
        }
    }
    printf("\n");

    return 0;
}



Submit