Why is this code failing 3 test cases?

#include
using namespace std;

struct B{
int h;
int l;
int r;
};

int main() {

long int n;
B a[100000];
a[0].l=0; 

cin>>n;

a[n-1].r=0;

cin>>a[0].h;
for(int i=1 ; i<n ; i++)
{
	cin>>a[i].h;
	
	//leftmost highest

	if(a[i-1].h<a[i-1].l)
	{
		a[i].l=a[i-1].l;
	}
	else
	{
		a[i].l=a[i-1].h;
	}
}	
    
//rightmost highest

for(int i=n-2; i>-1; i--)
{
	if(a[i+1].h>a[i+1].r)
	{a[i].r=a[i+1].h;}
	else
	{a[i].r=a[i+1].r;}
}

// water on top of each building

int sum=0,w=0;

for(int i=0 ; i<n ; i++)
{
  w=min(a[i].l,a[i].r)-a[i].h;
  if(w>0)
  {
   	   sum+=w;
  }
}

cout<<sum;
return 0;
}

Hey, you are unneccessary complicating the problem.
Please check this implementation from gfg.

`

#include<bits/stdc++.h>

using namespace std;

// Function to return the maximum

// water that can be stored

int maxWater( int arr[], int n)

{

// To store the maximum water

// that can be stored

int res = 0;

// For every element of the array

for ( int i = 1; i < n-1; i++) {

// Find the maximum element on its left

int left = arr[i];

for ( int j=0; j<i; j++)

left = max(left, arr[j]);

// Find the maximum element on its right

int right = arr[i];

for ( int j=i+1; j<n; j++)

right = max(right, arr[j]);

// Update the maximum water

res = res + (min(left, right) - arr[i]);

}

return res;

}

// Driver code

int main()

{

int arr[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};

int n = sizeof (arr)/ sizeof (arr[0]);

cout << maxWater(arr, n);

return 0;

}