Shubham and Tushar are 2 thieves and they had decided to rob a FALTU society. FALTU society consists of N houses in a row.Each of the ith house has A[i] number of gold coins.

To rob the whole society they both came up with a plan that they will make total N trips to the society one by one (starting from Shubham) and perform below operation in each trip :

First the thief (which is going to society) had to choose a house which is not selected in any of the previous trips and this house must be adjacent to the house chosen in the other thief’s last operation. Now assign this house to the current thief.If there are multiple such houses any of them can be chosen.

OR

If there is no such house that satisfies the above condition or this is Shuhbam's first trip then the thief can choose any house that is not selected before. Now the chosen house will be assigned to the current thief.

After these N trips , each thief can have the gold coins present in their assigned houses. They both love gold coins , and each of them is smart enough to perform the optimal moves in order to have the maximum number of gold coins at the end of the robbery.

Find the number of gold coins that each thief will have at the end of the robbery.

NOTE: Thief perform 2nd type of operation if he is unable to perform operation of 1st type.

This is a problem from hackerearth. In editorial the given solution is

#include<bits/stdc++.h>
using namespace std;
#define N 300010
typedef long long int ll;
inline ll read(){
	ll x=0,f=1;
	char c=getchar();
	while(c<'0'||c>'9'){
		if(c=='-')f=-1;
		c=getchar();
	}
	while(c>='0'&&c<='9'){
		x=(x<<1)+(x<<3)+c-'0';
		c=getchar();
	}
	return x*f;
}
ll odd,a[N],even,n,s[N];
bool check(ll x){
	ll mn=0;
	for(ll i=2;i<=n;++i){
		if(s[i-1]-mn>=x){
			mn=min(mn,s[i]);
		}
	}
	return s[n]-mn>=x;
}
int main(){
	n=read();
	for(ll i=1;i<=n;++i){
		a[i]=read();
		i&1?odd+=a[i]:even+=a[i];
	}
	if(!(n&1))return !printf("%lld %lld\n",max(odd,even),min(odd,even));
	for(ll i=1;i<=n;++i){
		s[i]=s[i-1]+(i&1?a[i]:-a[i]);
	}
	ll l=0,r=odd+even+1,ans=0;
	while(l<r){
		ll mid=(l+r)>>1;
		if(check(mid)){
			l=mid+1,ans=mid;
		}
		else{
			r=mid;
		}
	}
	printf("%lld %lld\n",even+ans,odd-ans);
	return 0;
}

I can't figure out what's going on here. Can someone shed some light?

Comments (1)