Recursive Vs Iterative

When i run my code without recursion (10^4 times), it takes 0-0.01 sec (according to Codechef IDE), but when i run it recursively (10^4 times), it takes 0.7-0.95 seconds, in both the cases same code is repeated equal number of times, then why execution time is higher in recursive? The code is below, in which if I comment line A(marked below), execution time is 0 sec, else it’s 0.7-0.95 sec, even though code is repeated for same number of time.

#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll couNt=0;
ll answer(vector<ll> H,vector<ll> A,ll b,ll c,ll f,ll npch=-1)
{
    ll ans=0,j,t,pch,k=c,val,vjh;
    t=b;
    b=c;
    c=t;
    if(b>c)
    {
        t=-1;
    }
    else
    {
        t=1;
    }
    ans=A[b];
    pch=b;
    for(j=b+t;j!=c+t;j+=t)
    {
        couNt++;
        
        if(H[j]>H[pch])
        {
            pch=j;
            ans+=A[j];
       
        }
        else if(j==c)
        {
            if(A[pch]==A[j])
            {
                ans=ans-A[pch]+A[j];
            
            }
            else
            {
                ans=-1;   
            }
        }
        else if(f!=-1 && H[j]<H[pch])
        {
        	/////////////////////////////////////////THIS LINE////////////////////////////////////////////
            j=answer(H,A,c,j,f,pch);  //this line line A
            if(j==c+t)
            	break;
            else
            {
            	pch=j;
            	ans+=A[j];
			}
        }
        if(npch!=-1 && f!=-1 && H[j]>H[npch])
        {
            break;
        }

    }
    if(f==-1)
        return ans;
    vjh=j;
    return vjh;
}
int main()
{
	ll T,N,i,j,a,b,c,ans,ansp,Q,t,pch,k,fnk,val;
	vector<ll> H,A,B;
	
	bool flg;
	cin>>N>>Q;
	for(i=0;i<N;++i)
	{
		
		scanf("%lld",&a);
		H.push_back(a);
	}
	for(i=0;i<N;++i)
	{
		scanf("%lld",&a);
		A.push_back(a);
		
	}
	if(N>1000 || Q>1000)
	{
	    answer(H,A,0,N-1,0);
	    cout<<couNt<<" ";
	    couNt=0;
	    answer(H,A,N-1,0,1);
	    cout<<couNt;
	}
	
	return 0;
}

Try passing the vectors by reference in the function arguments.

2 Likes

As @hetp111 pointed out, passing the vector by reference should significantly reduce the runtime. Passing vectors by value is an additional O(n), as the vector is copied each time the function is called!

3 Likes

Ok, Thanks.