feat: add trapping rain water (#1132)

* add trapping rain water.

* add short description of algorithm

* substitute min/max with define

* fix directory DIRECTORY.md

* chore: apply suggestions from code review

Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
Alexander Pantyukhin 2022-11-25 09:14:01 +04:00 committed by GitHub
parent 2f8fc8ca99
commit 7aba094afb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 29 additions and 1 deletions

View File

@ -26,6 +26,7 @@
| 29 | [Divide Two Integers](https://leetcode.com/problems/divide-two-integers/) | [C](./src/29.c) | Medium |
| 35 | [Search Insert Position](https://leetcode.com/problems/search-insert-position/) | [C](./src/35.c) | Easy |
| 38 | [Count and Say](https://leetcode.com/problems/count-and-say/) | [C](./src/38.c) | Easy |
| 42 | [Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) | [C](./src/42.c) | Hard |
| 53 | [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) | [C](./src/53.c) | Easy |
| 62 | [Unique Paths](https://leetcode.com/problems/unique-paths/description/) | [C](./src/62.c) | Medium |
| 66 | [Plus One](https://leetcode.com/problems/plus-one/) | [C](./src/66.c) | Easy |

27
leetcode/src/42.c Normal file
View File

@ -0,0 +1,27 @@
#define max(x,y)(((x)>(y))?(x):(y))
#define min(x,y)(((x)<(y))?(x):(y))
// Max stack. Runtime: O(n), Space: O(n)
// Algorithm description:
// - Calculate the stack of maximums from right board.
// - For each index find left maximum and right maximum of height
// - The each index if heights could place nor greater than minimum of left and right max minus curr height
// - Sum all index in result
int trap(int* height, int heightSize){
int* rightMaxStack = malloc(heightSize * sizeof(int));
rightMaxStack[heightSize - 1] = height[heightSize - 1];
for (int i = heightSize - 2; i >= 0; i--){
rightMaxStack[i] = max(rightMaxStack[i + 1], height[i]);
}
int leftMax = 0;
int result = 0;
for (int i = 0; i < heightSize; i++){
leftMax = max(leftMax, height[i]);
result += max(0, min(leftMax, rightMaxStack[i]) - height[i]);
}
free(rightMaxStack);
return result;
}