空地上竖立着n个从左到右排列的木板,它们可以把水挡住,但溢出最边上木板的水将会流到空地上。已知木板间距都是单位1,现给定每个木板的高度,请求出总共能接住的水量?说明一点,这里只考虑间距(宽度)和高度,不考虑第三个维度,因此水量是平方单位。
示例1,木板高度分别是2,1,3,那么我们可以接住2*2=4平方单位的水,如下图所示。注意,中间那个木板被水淹没了。
示例2,木板高度分别是2,4,3,那么可以接住2*1+3*1=5平方单位的水,如下图所示。
这个题在面试某金融公司的时候二面遇到了。
思路:最低的会被淹没,高的不会。所以从高的开始查。
1.找到最高的那块木板
2.从最高的那块木板向右找最高的木板,循环算出最右边的盛水量。
3.从最高的那块部门向左找最高的木板,循环计算出左边的盛水量。
代码如下,如有错误请指出。
public class WaterCapacity {
public static void main(String[] args) {
int[] arr = new int[]{5,5,5,2,1};
System.out.println(sumWater(arr));
}
public static int sumWater(int[] arr){
int maxIndex = findMax(arr,0,arr.length-1);
int left_sum = sumWater_left(arr,0,maxIndex);
int right_sum = sumWater_right(arr,maxIndex,arr.length-1);
return right_sum+left_sum;
}
public static int sumWater_left(int[] arr,int low,int high){
int leftsum = 0;
while(low<high){
int maxIndex = findMax(arr,low,high-1);
leftsum += (high - maxIndex)*arr[maxIndex];
high = maxIndex;
}
return leftsum;
}
public static int sumWater_right(int[] arr,int low,int high){
//找到右侧最大值和索引
int rightsum = 0;
while(low<high){
int maxIndex = findMax(arr,low+1,high);
rightsum += (maxIndex - low)*arr[maxIndex];
low = maxIndex;
}
return rightsum;
}
private static int findMax(int[] arr, int low, int high) {
int max = arr[low];
int maxIndex = low;
for(int i =low;i<=high;i++){
if(arr[i]>max){
max = arr[i];
maxIndex = i;
}
}
return maxIndex;
}
}