Code not giving any output, rain water harvesting problem

int cal(int n, int a[])
{
int maxsofar=0,index=0,ptr1=0,ptr2=0,sum=0,diff=0;
for(int i=0;i<n;i++)
{
if(a[i]==0)
{
continue;
}
else
{
ptr1=i;
ptr2=i+1;
maxsofar=0;

			index=i;
		}
	}
if(index==(n-1))
{return 0;}

while(ptr1<n)
{
	if(a[ptr2]>=a[ptr1])
	{
		diff=a[ptr1];
		for(ptr1;ptr1<ptr2;ptr1++)
		{
			sum+= (diff-a[ptr1]);
		}
		//maxsofar=a[ptr2];
		ptr1=ptr2;
		ptr2=ptr2+1;
		maxsofar=0;
	}
	else if(a[ptr2]<a[ptr1])
	{ 
		
		if(a[ptr2]>=maxsofar)
		{
			maxsofar=a[ptr2];
			index=ptr2;
		}
		ptr2++;
	}
	if(ptr2==(n-1))
	{
		if(maxsofar==0)
		{
			return sum;
		}
		else{
			for(ptr1+1;ptr1<index;ptr1++)
		       {
			     sum+= (maxsofar-a[ptr1]);
		      }
			  return sum;
			}
	}

}
return sum;

}

hey, you are using quite clumpsy approach, go for the approach mentioned in course video and try to code it. This is not a typical two pointer problem!

There is no video for this in course, that i know of. Also, i just wanna know that, why is nothing being printed.

Hey,
for(int i=0;i<n;i++)
{
if(a[i]==0)
{
continue;
}
else
{
ptr1=i;
ptr2=i+1;
maxsofar=0;

        index=i;
    }
}

if(index==(n-1))
{return 0;}
Here your index is n-1 always if a[n-1]!=0, so it just returns 0!!
Also refer to this for clear approach

1 Like

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.