Sherlock and Cost Discussions | Algorithms | HackerRank
  • + 4 comments
    #include<bits/stdc++.h>
    #define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL)
    using namespace std;
    typedef long long ll;
    ll mod = 1e9+7;
    ll dp[100001][101];
    ll Fun(ll idx, ll n, vector<ll>&B,ll previous){
        if (idx == n)return 0;
        if(dp[idx][previous]!=-1)return dp[idx][previous];
        ll ans = 0 , left  = 0;
        if(idx == 0)ans = max(Fun(idx+1,n,B,1),Fun(idx+1,n,B,B[idx]));
        else{
            left = max(abs(previous-1) + Fun(idx+1,n,B,1), abs(previous-B[idx])+Fun(idx+1,n,B,B[idx]));
            ans = max(ans,left);
        }
        return dp[idx][previous]=ans;
    }
    void Don(){
        ll n;
        cin >> n;
        vector<ll>B(n);
        for(int i = 0 ; i < n ; i++)cin >> B[i];
        memset(dp,-1,sizeof(dp));
        ll ans = Fun(0,n,B,0);
        cout<<ans<<endl;
    }
    int main(){
        ll t;
        cin >> t;
        while(t--){
            Don();
        }
    }
    /*
    instead of trying to place A[i] from 1 to B[i], just try 1 or B[i] because 1-B[i] gives us maximum.
    here is my solution using recursion to try all possible ways of keeping either 1 or B[i]
    after that i added memoization 
    */