Enable to clear certain test cases for the rain water harvesting problem

using namespace std;
int main() {
int n;
int a[1000]={0},l[1000]={0},r[1000]={0};
int t=0;
cin>>n;
for(int i=0; i<n; i++)
{
cin>>a[i];
}
l[0]=a[0];
r[n-1]=a[n-1];
for(int i=1; i<n; i++)
{
l[i]= max(l[i-1], a[i]);
}
for(int i=n-2; i>=0; i–)
{
r[i]=max(r[i+1], a[i]);
}
int x;
for(int i=0;i<n;i++)
{
x = min(l[i], r[i]) - a[i];
t+=x;
}
cout<<t;
return 0;
}

This code is able to pass most of the test cases but not all. Kindly tell the mistake and improvement.

hey igarg145!, the only problem is that you should add x to t only when x>0 as x = min(l[i], r[i]) - a[i] can be negative too!

Right! But now too, the first 4 test cases are not clearing… It is showing run time error.

See the size in problem its 1e6 and you are taking only 1e3 array sizes.

So now I changed it accordingly and most of test cases are passing but still 3 test cases shoe error.


you were using array size of 1e5 instead of 1e6

It was showing segmentation fault when I used 1e6

Okay!! I didn’t know that we could proceed even after segmentation fault.

https://ide.codingblocks.com/s/228675 this is just modificaton of your code and it is accepted!