Rain Water Harvesting

#include<bits/stdc++.h>
using namespace std;
int main() {
int a[1000];
int n;
cin>>n;

for(int i=0;i<n;i++){
	cin>>a[i];
}

int l[1000];
int r[1000];

l[0]=a[0];
r[0]=a[0];
int water=0;

for(int i=1;i<n;i++){
	l[i]=max(l[i-1],a[i]);
}
r[n-1]=a[n-1];

for(int i=n-2;i>=0;i--){
	r[i]=max(r[i+1],a[i]);
}

for(int i=0;i<n;i++){
	water+=min(l[i],r[i])-a[i];
}
cout<<water<<endl;
return 0;

}

this code is running for some test cases only.where is my mistake

got these issues:

  1. Take correct array sizes (as N=1000000 for some cases)
  2. Take long long as type to avoid any overflow.

min(l[i],r[i])-a[i] can be neagtive also!
do this way : long long x = min(l[i],r[i])-a[i];
if(x>0)
water+=x

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.