LeetCode 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 is able to trap after raining.

For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.


To solve the problem. the key point to find the maxHeight  index.


#include <vector>
#include <iostream>
#include <climits>
using namespace std;

/*
  Given n non-negative integers representing an elevation map where the width of each bar is 1.
  compute how much water it is able to trap after raining.
  For example:
  Given [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1], return 6.
*/

int trap(vector<int>& height) {
  int maxHeight = 0;
  int maxIndex = 0;
  for(int i = 0; i < height.size(); ++i) {
    if(maxHeight < height[i]) {
      maxHeight = height[i];
      maxIndex = i;
    }
  }
  int water = 0;
  int maxSoFar = 0;
  for(int i = 0; i < <strong>maxIndex</strong>; ++i) {
    if(height[i] < maxSoFar) water += (maxSoFar - height[i]); // less then maxSoFar can accumulate water.
    else maxSoFar = height[i];
  }

  maxSoFar = 0;
  for(int i = height.size() - 1; i > <strong>maxIndex</strong>; --i) {
    if(height[i] < maxSoFar) water += (maxSoFar - height[i]);  // less then maxSoFar can accumulate water.
    else maxSoFar = height[i];
  }
  return water;
}

int main(void) {
  vector<int> nums{0, 1, 0, 3, 1, 0, 1, 3, 2, 1, 2, 1};
  cout << trap(nums) << endl;
}


你可能感兴趣的:(LeetCode 42. Trapping Rain Water)