示例 1:

示例 2:
package DynamicProgramming;
public class p42_TrappingRainWater {
public static void main(String[] args) {
int[] height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
int res = trap(height);
System.out.println("res = " + res);
}
public static int trap(int[] height) {
int len = height.length;
int[] dpLeft = new int[len];
dpLeft[0] = height[0];
int[] dpRight = new int[len];
dpRight[len - 1] = height[len - 1];
int water = 0;
for (int i = 1; i < len; i++) {
dpLeft[i] = Math.max(dpLeft[i - 1], height[i]);
}
for (int i = len - 2; i >= 0; i--) {
dpRight[i] = Math.max(dpRight[i + 1], height[i]);
}
for (int i = 1; i <= len - 1; i++) {
int level = Math.min(dpLeft[i], dpRight[i]);
water += Math.max(0, level - height[i]);
}
return water;
}
}
#include
#include
#define max(a,b) ((a) > (b) ? (a) : (b))
#define min(a,b) ((a) > (b) ? (b) : (a))
int trap(int* height, int heightSize)
{
int* dpLeft = (int*)malloc(sizeof(int) * heightSize);
dpLeft[0] = height[0];
int* dpRight = (int*)malloc(sizeof(int) * heightSize);
dpRight[heightSize - 1] = height[heightSize - 1];
int water = 0;
for (int i = 1; i < heightSize; i++)
{
dpLeft[i] = max(dpLeft[i - 1], height[i]);
}
for (int i = heightSize - 2; i >= 0; i--)
{
dpRight[i] = max(dpRight[i + 1], height[i]);
}
for (int i = 1; i < heightSize - 1; i++)
{
int level = min(dpLeft[i], dpRight[i]);
water += max(0, level - height[i]);
}
return water;
}
/*主函数省略*/
Java语言版

C语言版
