You are given an array A of size N. The array contains integers and is of even length. The elements of the array represent N coin of values V1, V2, ….Vn. You play against an opponent in an alternating way.
In each turn, a player selects either the first or last coin from the row, removes it from the row permanently, and receives the value of the coin.
You need to determine the maximum possible amount of money you can win if you go first.
Note: Both the players are playing optimally.
- Time : O(n * n)
- Space : O(n * n)
We can choose only one arr[l], arr[r] at once, and our goal is make largest sum.
In this case, we choose the way to get maximum difference if we pick arr[l] or arr[r].
So, the result helper
returns maximum difference of we choose first.
We named as first pick sum as A
ans second pick sum as B
and helper
returns max(A - B)
. Also we know A + B
is sum(arr)
.
With Two formula we can calculate A
with simple math.
A + B = sum(arr)
A - B = helper(arr)
Two formula can be convert to 2 * A = sum(arr) + helper(arr)
.
So we just return (sum(arr) + helper(arr)) / 2
.
1 | class Solution{ |