Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6
class Solution {
public int trap(int[] height) {
int arrLength = height.length;
int total = 0;
if(arrLength<=2) return total;
int[] leftMaxArr = new int[arrLength];
int[] rightMaxArr = new int[arrLength];
leftMaxArr = leftMax(leftMaxArr, height);
rightMaxArr = rightMax(rightMaxArr, height);
for(int i=0; i<arrLength; i++){
if(leftMaxArr[i]<=rightMaxArr[i] && leftMaxArr[i]>height[i]){
total = total + (leftMaxArr[i]-height[i]);
}else if(rightMaxArr[i]<leftMaxArr[i] && rightMaxArr[i]>height[i] ){
total = total + (rightMaxArr[i]-height[i]);
}
}
return total;
}
public int[] leftMax(int[] arr, int[] height){
int max = height[0];
for(int i =0;i<height.length;i++){
if(max>height[i]){
arr[i] = max;
}else{
arr[i] = height[i];
max = height[i];
}
}
return arr;
}
public int[] rightMax(int[] arr, int[] height){
int max = height[height.length-1];
for(int i =height.length-1;i>=0;i--){
if(max>height[i]){
arr[i] = max;
}else{
arr[i] = height[i];
max = height[i];
}
}
return arr;
}
}
Here is the video explanation
Question : Given an array of integers A, return the largest integer that only occurs once.…
Jump search algorithm is a pretty new algorithm to search for an element in a…
What is Knuth Morris Pratt or KMP algorithm ? KMP is an algorithm which is…
Binary Search is a Logarithmic search which finds the target element in a sorted array…
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol Value I 1 V 5 X…
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such…
This website uses cookies.