Question: How much water can be injected between these bricks?
In fact, there are three main parts
1, take out the maximum height of these bricks and the second largest height
2, the second large height is multiplied by the distance between the maximum height and the second largest height, minus the middle bricks, and how much water can be injected between the maximum height and the second largest height.
3, respectively, to the maximum height and the second largest part of a recursive, the final value
Package Com.test;public class test{static int result = 0; End result static int[] wallheights = new int[] {1,6,1,2,3,4,100,1,9}; Represents the height of all walls public static void process (int start, int end) {//First:start and end of the highest wall//second:st The second high wall between art and end int first = 0, second = 0; FirstIndex: Index of the first high wall in Wallheights//secondindex: Index of the second-highest wall in wallheights int firstindex = 0, Secondindex = 0; Two walls must have at least one wall of distance if (End-start <= 1) return; Start getting the number of bricks for the first high and second walls//bubbling for (int i = start+1; I <= end; i++) {if (Wallheights[i]>wallheig Hts[secondindex]) {if (Wallheights[i]>wallheights[firstindex]) {///if it is greater than the second largest, then I is the first large, the first big becomes the second largest secondindex = FirstIndex; FirstIndex = i; } else {//if it is larger than the second and larger than the first size, then I is a sophomore, the first large invariant secondindex = i; }}} first = Wallheights[firstindex]; System.out.println ("FirstIndex" +firstindex); System.out.println ("first" +first); Second = Wallheights[secondindex]; System.out.println ("Secondindex" +secondindex); System.out.println ("second" +second); Gets the index of the left wall int startIndex = Math.min (FirstIndex, Secondindex); Gets the index of the right wall int endIndex = Math.max (FirstIndex, Secondindex); calculates the distance int distance = Endindex-startindex; If there is at least one wall between the first high wall and the second high wall, start calculating how many units of water can be placed between the two walls if (Distance > 1) {result = result + (Distan CE-1) * SECOND; Subtract the number of bricks between the two walls for (int i = StartIndex + 1; i < EndIndex; i++) {Result-= Wallhe Ights[i]; }}//Start recursive processing how much water can be placed on the left wall from the start position (start, startIndex); How many water processes (endIndex, end) can be placed at the end of the right wall distance at the beginning of recursion? } public static void Main (string[] args) {process (0, wallheights.length-1); System.out.println (result); }}
on the basis of this article to change, the middle part is not quite clear, replaced by their own
http://blog.csdn.net/nokiaguy/article/details/14023225
Algorithm problem-Water flooding