LeetCode //42. Trapping Rain Water

42. Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

 

Example 1:

LeetCode //42. Trapping Rain Water_第1张图片

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

Example 2:

Input: height = [4,2,0,3,2,5]
Output: 9

Constraints:

  • n == height.length
  • 1 < = n < = 2 ∗ 1 0 4 1 <= n <= 2 * 10^4 1<=n<=2104
  • 0 < = h e i g h t [ i ] < = 1 0 5 0 <= height[i] <= 10^5 0<=height[i]<=105

From: LeetCode
Link: 42. Trapping Rain Water


Solution:

Ideas:
In this solution, leftMax and rightMax are two arrays storing the maximum height of bar from the start up to index i and from the end to index i, respectively.
In the final loop, for each index i, it finds the smaller of leftMax[i] and rightMax[i], and subtracts the height of bar at index i from it, and adds it to totalWater.
Finally, it frees the allocated memory for leftMax and rightMax before returning totalWater.
Code:
int trap(int* height, int heightSize){
    if(heightSize == 0) {
        return 0;
    }

    int* leftMax = (int*)malloc(heightSize * sizeof(int));
    int* rightMax = (int*)malloc(heightSize * sizeof(int));

    leftMax[0] = height[0];
    for(int i = 1; i < heightSize; i++) {
        leftMax[i] = height[i] > leftMax[i - 1] ? height[i] : leftMax[i - 1];
    }

    rightMax[heightSize - 1] = height[heightSize - 1];
    for(int i = heightSize - 2; i >= 0; i--) {
        rightMax[i] = height[i] > rightMax[i + 1] ? height[i] : rightMax[i + 1];
    }

    int totalWater = 0;
    for(int i = 0; i < heightSize; i++) {
        totalWater += (leftMax[i] < rightMax[i] ? leftMax[i] : rightMax[i]) - height[i];
    }

    free(leftMax);
    free(rightMax);

    return totalWater;
}

你可能感兴趣的:(LeetCode,leetcode,算法,c语言)