如图题目要求。
#include <iostream>
using namespace std;
int Volume(int * Height,int n);
int main()
{
int sum = 0;
int H[11] = {1,2,0,1,0,1,3,1,0,2,1} ;
sum = Volume(H,11);
cout<<sum<<endl;
getchar();
return 0;
}
int Volume(int * Height,int n)
{
//要想能够装住水,必须两边高中间低,就像河流,两边高,中间洼才能有水。
//代码的主要思想:持续寻找从数组两头寻找河的两边高地,先不管中间是否有新的高地,
//只要目前的高地能够圈住水,那就求出能够最大装水量,以此类推。
int L = Height[0];
int R = Height[n-1];
int temp=0;
int i = 0;
int j = n;
for(i;j-i>0;i++)
{
j = n-i-1;
if(L<Height[i])
{
L=Height[i];
}
if(R<Height[j])
{
R=Height[j];
}
if(Height[i]<L&&Height[i]<R)
{
if(L<=R)
{
temp = temp +(L-Height[i]);
}
else
{
temp = temp +(R-Height[i]);
}
}
if(Height[j]<L&&Height[j]<R&&i!=j)
{
if(L<=R)
{
temp = temp +(L-Height[j]);
}
else
{
temp = temp +(R-Height[j]);
}
}
}
return temp;
}