Rainwater harvesting que in array assignment

my code for rainwater harvesting que in array assignment is this can you tell me where i am doing wrong because all the hypothetical case i consider as input, the output is right.
#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;

}

The approach you are trying to use in your code is little bit wrong… I would suggest you to go through online video lecture on the same problem and then try to implement it…