October 2019

Joker And The Bank

Solution

Implementation


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
typedef long long int ll;
using namespace std;
int A[100005], P[100005];
 
int other_end[100005];
ll ans[100005], seg[100005];
 
int main()
{
    int n;
    cin>>n;
    for(int i=1; i<=n; ++i)
        cin>>A[i];
    for(int i=1; i<=n; ++i)
        cin>>P[i];
    ll res = 0; // initially all banks are destroyed
    for(int i=n; i>=1; --i)
    {
        ans[i] = res;
        int pos = P[i];
 
        ll sum = A[pos];
        int l = pos, r = pos;
        if(other_end[pos-1]!=0) // check to the left of the restored bank
        {
            l = other_end[pos-1]; // exisiting left of the current segment
            sum += seg[l];  // add segment with restored bank to the current bank
        }
        if(other_end[pos+1]!=0) // check to the right of the restored bank
        {
            sum += seg[pos+1]; // exisiting right of the current segment
            r = other_end[pos+1]; // add segment with restored bank to the current bank
        }
        other_end[l] =  r;
        other_end[r] = l;
        seg[l] = sum; // compute partial sum for current bank
        res = max(res,sum); // max net-worth segment with restored banks
    }
 
    for(int i=1; i<=n; ++i)
        cout<<ans[i]<<endl;
    return 0;
}