## 1690. Stone Game VII

Alice and Bob take turns playing a game, with Alice starting first.

There are `n` stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove.

Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference. Alice's goal is to maximize the difference in the score.

Given an array of integers `stones` where `stones[i]` represents the value of the `ith` stone from the left, return the difference in Alice and Bob's score if they both play optimally.

Example 1:

```Input: stones = [5,3,1,4,2]
Output: 6
Explanation:
- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4].
- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4].
- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4].
- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = .
- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = [].
The score difference is 18 - 12 = 6.
```

Example 2:

```Input: stones = [7,90,5,1,100,10,10,2]
Output: 122```

Constraints:

• `n == stones.length`
• `2 <= n <= 1000`
• `1 <= stones[i] <= 1000`

## Rust Solution

``````struct Solution;

impl Solution {
fn stone_game_vii(stones: Vec<i32>) -> i32 {
let n = stones.len();
let mut memo: Vec<Vec<i32>> = vec![vec![0; n]; n];
let sum = stones.iter().sum();
Self::dp(0, n - 1, &mut memo, &stones, sum)
}

fn dp(l: usize, r: usize, memo: &mut Vec<Vec<i32>>, stones: &[i32], sum: i32) -> i32 {
if l == r {
0
} else {
if memo[l][r] != 0 {
memo[l][r]
} else {
let mut res = 0;
res = res.max(sum - stones[l] - Self::dp(l + 1, r, memo, stones, sum - stones[l]));
res = res.max(sum - stones[r] - Self::dp(l, r - 1, memo, stones, sum - stones[r]));
memo[l][r] = res;
res
}
}
}
}

#[test]
fn test() {
let stones = vec![5, 3, 1, 4, 2];
let res = 6;
assert_eq!(Solution::stone_game_vii(stones), res);
let stones = vec![7, 90, 5, 1, 100, 10, 10, 2];
let res = 122;
assert_eq!(Solution::stone_game_vii(stones), res);
}
``````

Having problems with this solution? Click here to submit an issue on github.