828. Remove and Score
Rina and Jo work in a warehouse where crates stand on a long shelf, each marked with a positive value. They alternate turns, Rina first. On a turn the player removes either the leftmost or the rightmost crate, and then scores the combined value of all crates still left on the shelf. When the shelf is empty the game is over.
Rina wants to make her final total minus Jo's final total as large as possible, and Jo wants that difference as small as possible. Given stones, the crate values from left to right, return that difference when both play optimally. Aim for time O(n^2).
Example 1
- Input:
- stones = [14,3,9,22,5]
- Output:
- 23
- Explanation:
With perfect play the first player finishes
23points ahead.
Example 2
- Input:
- stones = [12,12]
- Output:
- 12
- Explanation:
Whichever end the first player takes, the single remaining crate is worth 12 to her, so the margin is
12.
Example 3
- Input:
- stones = [4,18,6,11,2,9]
- Output:
- 38
- Explanation:
Choosing ends greedily is not always best here; the optimal margin is
38.
Constraints
1 ≤ stones.length ≤ 1000
1 ≤ stones[i] ≤ 1000
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,000 msC++ 250 msJava 500 msJavaScript 500 msTypeScript 500 ms
Expected complexity
- Time
- O(n^2)
- Space
- O(n)