Why this is only giving one case right?
hello @dhruvilcodes
greedy approach will not work in this problem becuase nimit is also playing optimally. so when nimit turns will come, he will also try to play wisely and try to maximize his score or minimize piyush score.
so what step nimit will take is also important. also picking always local maximum doesnt ensure that overall sum will be maximum.
refer this for clarity->
overall we have two possibilities at each instance.
For the first possibility , where we could pick the first element , the other player will pick the next element from the side that would minimise our total score.
Similarly , for the second possibility , where we can pick the last element , the other player would still pick the next element from the side that would minimise our total score.
We entertain both these cases and take the maximum result of the two and return that result.
ll optimalGame(ll i,ll j){
if(i > j){
return 0;
}
// Consider both the possibilities. You can pick either the first or the last coin.
// Since the opponent plays optimally , we would get the minimum of the remaining coins for each choice.
ll pickFirst = coins[i] + min( optimalGame(i+2,j) , optimalGame(i+1,j-1) ) ;
ll pickLast = coins[j] + min( optimalGame(i,j-2) , optimalGame(i+1,j-1) ) ;
// Pick the max of two as your final result
ll ans = max(pickFirst,pickLast);
return ans;
}
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.