add prob 11

This commit is contained in:
2025-08-24 23:45:17 +08:00
parent febe7547bf
commit a63b2a69af

42
11-42.c Normal file
View File

@@ -0,0 +1,42 @@
#include <stdio.h>
int trap(int* height, int heightSize) {
int ans = 0;
int max = 0;
int max_x = 0;
for (int i = 0; i < heightSize; ++i) {
if (height[i] > max) {
max = height[i];
max_x = i;
}
}
// left part
int curleft = 0;
for (int i = 0; i < max_x; ++i) {
if (height[i] >= curleft) {
curleft = height[i];
}
else {
ans += curleft - height[i];
}
}
// right part
int curright = 0;
for (int i = heightSize - 1; i > max_x; --i) {
if (height[i] >= curright) {
curright = height[i];
}
else {
ans += curright - height[i];
}
}
return ans;
}
int main() {
int height[] = {4,2,0,3,2,5};
printf("%d\n", trap(height, sizeof(height) / sizeof(int)));
return 0;
}