What wrong with this logic

It is passing only one test case…
What is wrong here

@ashishnnnnn your logic is incorrect, you are using greedy approach which will give WA.

Consider both possibilities, and take max when it’s your turn and min when its opponents turn!

But here players are playing optimally … then why should i consider min…when its opponents turn

this is the reason itself, when it’s your turn, you try to maximize your coins, but when its opponents turn, he tries to maximize his coins (or minimize your coins!)

Do we need The help of D.P to solve this question…
Because as you said that when it’s my turn i should select maximum…which i am doing…

DP optimization is possible,
you are doing it greedily!
by max I mean this max(arr[i] + solve(i+1,j), arr[j] + solve(i,j-1) )
here I don’t compare arr[i] and arr[j]
I try both options ans then take maximum out of them!
try to think this way

Hii here by doing this max(arr[i] + solve(i+1,j), arr[j] + solve(i,j-1) ) we are only considering about the first palyer that he should be come up with maximum and other one minimum… sorry if i am missing something… Not able to get it

See we first have to know whose turn it is to pick coin, after that we do this:
if((i+j)%2) // piyush’s turn
dp[i][j] = max(a[i]+dp[i+1][j],a[j]+dp[i][j-1])
else //Nimit’s turn
dp[i][j] = min(dp[i+1][j],dp[i][j-1])
here dp[i][j] is maximum coins collected by piyush when coins remaining from index i to index j.
so answer is dp[0][n-1]
If you still can’t get it, I would recommend you to unlock editorial.

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.