problems / 126

Backlog From Both Ends

medium games dp prefix-sums arrays 1000 ms · 256 MB

Backlog From Both Ends

At the end of every sprint, two engineers, Dana and Eli, split the leftover backlog between them for the bonus round. The backlog is a row of n tickets, and ticket i (counting from the front) is worth p_i story points. Dana moves first, and then they alternate. On each turn the engineer whose turn it is claims exactly one ticket. It must be either the ticket currently at the front of the backlog or the one currently at the back, and it is removed from the row. This continues until every ticket has been claimed.

Each engineer wants to end up with as many story points as possible, and both play optimally, knowing every ticket's value. Find how many story points each of them ends up with.

Input

The first line contains n (1 ≤ n ≤ 5000), the number of tickets.

The second line contains n integers p_1, p_2, ..., p_n (0 ≤ p_i ≤ 10^9), the story points of the tickets from front to back.

Output

Print two integers separated by a space: Dana's total and Eli's total.

Notes

In the first example the backlog is 3 9 1 2. Taking the larger end ticket (the 3) is a mistake for Dana: Eli then takes the 9, and Dana finishes with only 5 points. Dana should take the 2 instead. Whatever Eli then takes, Dana can claim the 9, finishing with 11 points and leaving Eli with 4.

In the second example the order of claims does not matter: Dana makes three of the five claims.

The totals can exceed the range of a 32-bit integer.

Example 1

Input

4
3 9 1 2

Output

11 4

Example 2

Input

5
2 2 2 2 2

Output

6 4

Hints · reveal one at a time if you're stuck

Hint 1

Taking the bigger end is not always right, because it can hand the opponent a bigger ticket next turn. Think about what the position looks like after one claim: which tickets are still unclaimed, and who moves?

Hint 2

The unclaimed tickets are always one contiguous window, and the total points are fixed, so the game is zero-sum: track the mover's advantage over the opponent on each window. How does the advantage on a window depend on the advantages of the two smaller windows you can leave behind?

Hint 3

Compute these advantages for windows in order of increasing length, so each step only needs the previous length. You can keep a single array of values, updating it in place, since each new window only needs the two windows one shorter. Use 64-bit integers for the totals.

report an issue Prefer your own editor? sooks prep 126 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.