Skip to content

Commit abe91d8

Browse files
author
Daniel Nallapalli
committed
Solution #496 (C) - Daniel - 16/06/2025 - commit Dijkstra-Edu#2
1 parent ffe67a8 commit abe91d8

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Note: The returned array must be malloced, assume caller calls free().
3+
*/
4+
#define MAX_NUM 10001
5+
6+
int* nextGreaterElement(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
7+
int* result = (int*)malloc(sizeof(int) * nums1Size);
8+
int next_greater[MAX_NUM];
9+
int stack[MAX_NUM];
10+
int top = -1;
11+
12+
for (int i = 0; i < MAX_NUM; i++) {
13+
next_greater[i] = -1;
14+
}
15+
16+
for (int i = 0; i < nums2Size; i++) {
17+
int current = nums2[i];
18+
while (top >= 0 && current > stack[top]) {
19+
int prev = stack[top--];
20+
next_greater[prev] = current;
21+
}
22+
stack[++top] = current;
23+
}
24+
25+
for (int i = 0; i < nums1Size; i++) {
26+
result[i] = next_greater[nums1[i]];
27+
}
28+
29+
*returnSize = nums1Size;
30+
return result;
31+
}

0 commit comments

Comments
 (0)