1761. Front Minus Back

Hard7.5 points estimatedHeapPrefix SumGreedy

A warehouse shelf holds a row of 3n crates, where nums[i] is the value of the crate at position i. The manager must remove exactly n crates of her choice. The 2n crates that remain keep their original order; the first n of them are placed on the front shelf and the last n on the back shelf. The manager wants the front shelf to be as valuable as possible and the back shelf as cheap as possible, so the score of a plan is (sum of front values) minus (sum of back values).

Given nums (its length is a multiple of 3, and n is that length divided by 3), return the maximum score over all ways to remove n crates. The score can be negative or exceed 32 bits, so return a long. The intended solution runs in O(n log n) time and O(n) space.

Example 1

Input:
nums = [3,1,2]
Output:
2
Explanation:

With n = 1, remove the crate worth 2: the remaining row is [3, 1], giving front 3 minus back 1 = 2, which beats the other two removals.

Example 2

Input:
nums = [5,5,5]
Output:
0
Explanation:

All crates are equal, so whatever is removed the front and back shelves have the same value and the score is 0.

Example 3

Input:
nums = [7,9,5,2,6,8]
Output:
9
Explanation:

With n = 2, remove the crates worth 6 and 8: the remaining row [7, 9, 5, 2] has front 7 + 9 = 16 and back 5 + 2 = 7, so the score is 9.

Constraints

nums.length == 3n, 1 ≤ n ≤ 5 * 104

1 ≤ nums[i] ≤ 109

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,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…