Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.LinkedList;
- public class rainQ{
- public static void main(String [] args){
- int[][] heights = {
- {2,5,1,2,3,4,7,7,6},
- {3,2,1},
- {2,2,1,1,2},
- {5,3,2,1,2,3,4,5,4,3,0,5},
- {2,1,2,1,2},
- {3,2,1,2,1,2,0,2,3},
- {3,1,0,2},
- {},
- {0},
- {1,1},
- {0,0,0},
- {2,5,1,3,1,2,1,7,7,6},
- {5,3,2,1,2,3,4,5,4,3,0,4}
- };
- int[] answers = {10,
- 0,
- 2,
- 23,
- 2,
- 11,
- 3,
- 0,
- 0,
- 0,
- 0,
- 17};
- rainQ rQ = new rainQ();
- for(int i = 0; i < heights.length; i++){
- boolean correct = (answers[i] == rQ.rainArea(heights[i]));
- if(correct){
- System.out.println("Result " + i + " is " + correct);
- } else {
- System.out.println("Result " + i + " is false.");
- }
- System.out.println();
- }
- }
- public int rainArea(int[] heights){
- // There can't be a wall if there's only 2 elements
- if(heights.length < 3){
- return 0;
- }
- // The derivative of the differences
- int[] changeMatrix = new int[heights.length];
- // Set the first height as the first derivative
- changeMatrix[0] = heights[0];
- boolean trap = false;
- int totalArea = 0, tempArea = 0;
- int maxHeight = 0;
- int length = 0;
- boolean valid = false;
- // Calculate the rest of the heights
- for(int i = 1; i < heights.length; i++){
- changeMatrix[i] = heights[i] - heights[i-1];
- if(trap == true) length++;
- if(trap==false && changeMatrix[i] < 0){
- maxHeight = heights[i-1];
- tempArea += (maxHeight - heights[i]);
- trap = true;
- //System.out.println(tempArea);
- } else if(trap == true && maxHeight-heights[i] > 0 && !(i == heights.length-1)) {
- tempArea += (maxHeight - heights[i]);
- //System.out.println(tempArea);
- if(changeMatrix[i] > 0){
- valid = true;
- }
- } else if(trap == true && maxHeight-heights[i] <= 0 || i == heights.length-1){
- if(changeMatrix[i]>0){
- valid = true;
- }
- if(heights[i] < maxHeight){
- tempArea += length * (heights[i] - maxHeight);
- //System.out.println(tempArea);
- }
- if(valid) totalArea+=tempArea;
- tempArea = 0;
- trap = false;
- maxHeight = heights[i];
- length = 1;
- valid = false;
- }
- }
- return totalArea;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement