Skip to content

Commit d84424f

Browse files
authored
Merge pull request neetcode-gh#2762 from mdmzfzl/0239_Sliding_Window_Maximum
Added 0239-sliding-window-maximum.c
2 parents ab1fcb0 + 14ded94 commit d84424f

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

c/0239-sliding-window-maximum.c

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
typedef struct {
5+
int value;
6+
int index;
7+
} Pair;
8+
9+
typedef struct {
10+
Pair* data;
11+
int front;
12+
int rear;
13+
int size;
14+
} Deque;
15+
16+
// Create a new deque
17+
Deque* createDeque(int size) {
18+
Deque* deque = (Deque*)malloc(sizeof(Deque));
19+
deque->data = (Pair*)malloc(size * sizeof(Pair));
20+
deque->front = 0;
21+
deque->rear = -1;
22+
deque->size = 0;
23+
return deque;
24+
}
25+
26+
// Push a new element to the back of the deque
27+
void pushBack(Deque* deque, int value, int index) {
28+
while (deque->size > 0 && value >= deque->data[deque->rear].value) {
29+
deque->rear--;
30+
deque->size--;
31+
}
32+
deque->rear++;
33+
deque->data[deque->rear].value = value;
34+
deque->data[deque->rear].index = index;
35+
deque->size++;
36+
}
37+
38+
// Pop elements from the front of the deque
39+
void popFront(Deque* deque, int index) {
40+
if (deque->size > 0 && deque->data[deque->front].index == index) {
41+
deque->front++;
42+
deque->size--;
43+
}
44+
}
45+
46+
// Calculate the maximum sliding window
47+
int* maxSlidingWindow(int* nums, int numsSize, int k, int* returnSize) {
48+
// Check if the input array is empty
49+
if (numsSize == 0) {
50+
*returnSize = 0;
51+
return NULL;
52+
}
53+
54+
// Calculate the size of the result array
55+
*returnSize = numsSize - k + 1;
56+
57+
// Allocate memory for the result array
58+
int* result = (int*)malloc((*returnSize) * sizeof(int));
59+
60+
// Create a deque (double-ended queue) to efficiently track maximum elements
61+
Deque* deque = createDeque(numsSize);
62+
63+
// Iterate through the input array
64+
for (int i = 0; i < numsSize; i++) {
65+
// Push the current element to the deque, maintaining the maximum at the front
66+
pushBack(deque, nums[i], i);
67+
68+
// Check if the window has reached the required size
69+
if (i >= k - 1) {
70+
// Store the maximum element in the result array
71+
result[i - k + 1] = deque->data[deque->front].value;
72+
73+
// Pop elements from the front of the deque that are outside the current window
74+
popFront(deque, i - k + 1);
75+
}
76+
}
77+
78+
// Free memory allocated for the deque
79+
free(deque->data);
80+
free(deque);
81+
82+
// Return the result array containing maximum elements in each sliding window
83+
return result;
84+
}

0 commit comments

Comments
 (0)