1730. Prefix Median Cost

Medium3.5 points estimatedHeapData StreamGreedy

A sensor network streams in the readings of nums one at a time. After each reading arrives, the engineers want to know how much total adjustment it would take to bring every reading received so far to one common integer value t. Adjusting a reading x costs |x - t|, and t may be chosen freely to make the total as small as possible (a median of the readings always works).

Return a long[] of length n whose i-th entry is that minimum total cost for the prefix nums[0..i]. The answer is unique, so no tie-break is needed. Aim for O(n log n) time and O(n) space.

Example 1

Input:
nums = [5,1,3]
Output:
[0,4,4]
Explanation:

The prefixes cost 0, 4 (any t between 1 and 5) and 4 (t = 3: 2 + 2 + 0).

Example 2

Input:
nums = [2,9,2,9]
Output:
[0,7,7,14]
Explanation:

Prefix [2,9,2] costs 7 with t = 2, and [2,9,2,9] costs 14 with any t in [2, 9].

Constraints

1 ≤ n ≤ 105

-109 ≤ nums[i] ≤ 109

Every cost fits in a 64-bit signed integer.

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 3,400 msC++ 850 msJava 1,700 msJavaScript 1,700 msTypeScript 1,700 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…