Files
C/leetcode/src/42.c
Alexander Pantyukhin 7aba094afb 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>
2022-11-24 23:14:01 -06:00

28 lines
957 B
C

#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;
}