Skip to content

Commit c442979

Browse files
authored
Create: 1964-find-the-longest-valid-obstacle-course-at-each-position.c
1 parent d8a4758 commit c442979

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
int upperBound(int *arr, int size, int target) {
2+
int left = 0, right = size - 1;
3+
while (left <= right) {
4+
int mid = left + (right - left) / 2;
5+
if (arr[mid] <= target) {
6+
left = mid + 1;
7+
} else {
8+
right = mid - 1;
9+
}
10+
}
11+
return left;
12+
}
13+
14+
int* longestObstacleCourseAtEachPosition(int* obstacles, int obstaclesSize, int* returnSize) {
15+
int* lis = (int*)malloc(obstaclesSize * sizeof(int));
16+
int* result = (int*)malloc(obstaclesSize * sizeof(int));
17+
*returnSize = obstaclesSize;
18+
19+
int lisSize = 0;
20+
21+
for (int i = 0; i < obstaclesSize; ++i) {
22+
int x = obstacles[i];
23+
if (lisSize == 0 || lis[lisSize - 1] <= x) {
24+
lis[lisSize] = x;
25+
result[i] = lisSize + 1;
26+
lisSize++;
27+
} else {
28+
int idx = upperBound(lis, lisSize, x);
29+
lis[idx] = x;
30+
result[i] = idx + 1;
31+
}
32+
}
33+
34+
free(lis);
35+
return result;
36+
}

0 commit comments

Comments
 (0)