Rainwater problem in arrays assignmnet

doubt in rainwater harvesting problem in arrays assignment
#include
#include
using namespace std;

int main() {
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
int hi=0,g;
for(int i=0;i<n;i++){
hi=max(hi,a[i]);
}
for(int i=0;i<n;i++){
if(a[i]==hi){
g=i;
break;
}
}
int sum=0;
int temphi=hi,tempg=g,p;
while(p>0){

	int lh=0;
	for(int i=0;i<tempg;i++){
		lh=max(lh,a[i]);
	}
	int h;
	for(int i=0;i<tempg;i++){
		if(a[i]==lh){
			h=i;
			break;
		}
	}
	for(int i=tempg-1;i>h;i--){
		sum=sum+lh-a[i];
	}
	temphi=lh;
	p=h;
	tempg=h;
}
tempg=g;
temphi=hi;
while(p<n-1){
	int lh=0;
	for(int i=tempg+1;i<n;i++){
		lh=max(lh,a[i]);
	}
	int h;
	for(int i=tempg+1;i<n;i++){
		if(a[i]==lh){
			h=i;
			break;
		}
	}
	for(int i=tempg+1;i<h;i++){
		sum=sum+lh-a[i];
	}
	temphi=lh;
	p=h;
	tempg=h;
}	
cout<<sum;
return 0;

}
this is my code it is working totally fine with some of my assumed cases but on submitting it produces wrong ans can you point out the mistake that i was making