Note: The numbers can be arbitrarily large and are non-negative.
public class Solution { public int trap(int[] A) { // Suppose the volume of the trapped water in position i is volume(i) // volume(i) depends on the most height bar before and after it --- maxLHeight[i] and maxRHeight[i] // volume(i) = min{maxLHeight[i], maxRHeight[i]}-A[i] if min{maxLHeight[i], maxRHeight[i]} > A[i] int n = A.length; if (n <= 2) return 0; int volume = 0; // The sum volume of trapped water int[] maxLHeight = new int[n]; int[] maxRHeight = new int[n]; for (int i = 1; i < n; i++) maxLHeight[i] = Math.max(maxLHeight[i-1], A[i-1]); for (int i = n-2; i >= 0; i--) maxRHeight[i] = Math.max(maxRHeight[i+1], A[i+1]); for (int i = 0; i < n; i++) if (Math.min(maxLHeight[i], maxRHeight[i]) > A[i]) volume += Math.min(maxLHeight[i], maxRHeight[i]) - A[i]; return volume; } }
No comments:
Post a Comment