Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
1,486 views
You always start from index "1" , you have to reach index "N".

 

Example : N = 4 .

Output :     2

Way-1 : 1-->2-->3-->4

Way-2 : 1-->4
in Algorithms and Problems by Expert (108,100 points) | 1,486 views

1 Answer

1 like 0 dislike
Best answer

We can use straightforward dynamic programming . 

Let dp[i] be the number of ways to reach index 'i' of the array . 

dp[1]=1 , dp[2] = 1 , dp[3] = 1 , dp[4] = 2 will be Base cases.

If you are at index 'i' , you can reach it , either from index 'i-1' or index 'i-3' ,  so dp[i] = dp[i-1] + dp[i-3] . 

Recurrence relation has been formed and we are done! Voial !

O(N) 

Code : 

#include<bits/stdc++.h>
using namespace std ; 
typedef long long int ll ; 
#define rep(i, l, r) for ((i) = (l); (i) <=(r); (i)++)
#define rep1(i, r, l) for ((i) = (r); (i) >=(l); (i)--)
int main()
{
    ll n ; 
    cin>>n; 
    ll dp[n+3]; 
    ll i ; 
    dp[1]=1;
    dp[2]=1;
    dp[3]=1;  
    dp[4]=2 ; 
    rep(i,5,n)
    {
        dp[i] = dp[i-3] + dp[i-1] ; 
    }
    cout<<dp[n]; 
    
    
    return 0 ; 
}

by
selected by

Get best answers to any doubt/query/question related to programming , jobs, gate, internships and tech-companies. Feel free to ask a question and you will receive the best advice/suggestion related to anything you ask about software-engineering , development and programming problems .