https://oj.leetcode.com/problems/trapping-rain-water/
Http://fisherlei.blogspot.com/2013/01/leetcode-trapping-rain-water.html
Public class solution { public int trap (Int[] A) { // for a coordinate has // - leftmax It left highest // - rightmax it right up // - val it itself highly // then its volume is max ( min (Leftmax, rightmax) - val, 0 ) // traverse from left to right create leftmax[] // similar right-to-left traversal Create rightmax[] // finally traverse through calculate volume sum // o (n) // Input validations. if (a == null | | a.length == 0) return 0; // Invalid input. int len = A.length; // Build leftmax[] int[] leftmax = new int[len]; int seenleftmax = 0; for (int i = 0 ; i < len ; i ++) { leftmax[i] = seenleftmax; if (A[i] > seenleftmax) seenleftmax = A[i]; } // Build rightmax[] int[] rightmax = new int[len]; int seenrightmax = 0; for (int i = len - 1 ; i >= 0 ; i --) { rightmax[i] = seenrightmax; if (A[i] > Seenrightmax) seenrightmax = a[i]; } // Calculate result int result = 0; for (int i = 0 ; i < len ; i ++) { Int v = math.max (Math.min (Leftmax[i], rightmax[i]) - a[i] , 0); result += v; } return result; }}
[Leetcode]42 trapping Rain water