1755. Regret Trader

Hard7.5 points estimatedHeapGreedy

A market stall owner sees the price of one commodity on each of n days, given in prices. On each day the owner may buy exactly one unit, sell exactly one unit that is currently held, or do nothing. There is no limit on how many units can be held at once, and the owner cannot sell a unit that was not bought on an earlier day. Units not sold by the end are simply worth nothing, so the owner wants to maximise the cash gained from sales minus the cash spent on purchases. Return the maximum possible profit as a long. A quadratic table over days and holdings is too slow; the intended solution uses a heap and runs in O(n log n) time with O(n) space. Here n is at most 10^5 and prices are at most 10^6.

Example 1

Input:
prices = [1,5,2,8]
Output:
10
Explanation:

Buy at 1 and sell at 5, then buy at 2 and sell at 8, earning 4 + 6 = 10.

Example 2

Input:
prices = [3,2,1]
Output:
0
Explanation:

Prices only fall, so any trade loses money and the best profit is 0.

Constraints

1 ≤ n = prices.length ≤ 105; 1 ≤ prices[i] ≤ 106.

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,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 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…