mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-25 14:59:36 +03:00
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:
parent
2f8fc8ca99
commit
7aba094afb
@ -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 |
|
||||
|
@ -74,4 +74,4 @@ git push origin solution/your-solution-name:solution/your-solution-name
|
||||
|
||||
4. You're done now! You just have to make a [**pull request**](https://github.com/TheAlgorithms/C/compare). 🎉
|
||||
|
||||
If you need any help, don't hesitate to ask and join our [**Discord server**](https://the-algorithms.com/discord)! 🙂
|
||||
If you need any help, don't hesitate to ask and join our [**Discord server**](https://the-algorithms.com/discord)! 🙂
|
27
leetcode/src/42.c
Normal file
27
leetcode/src/42.c
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user