leetcode 之trap water(8)
这题不太好想。可以先扫描找到最高的柱子,然后分别处理两边:记录下当前的局部最高点,如果当前点小于局部最高点,加上,
反则,替换当前点为局部最高点。
int trapWater(int A[], int n) { int peak = 0; int max = 0; int water = 0; for (int i = 1; i < n; i++) { if (A[i]>A[max])max = i; } for (int i = 0; i < max; i++) { if (A[i]>peak) peak = A[i]; else water += peak - A[i]; } for (int j = n - 1; j > max; j--) { if (A[j]>peak) peak = A[j]; else water += peak - A[j]; } return water; }