Ad platform~15 min2s · 256 MBtarget O(n) time, O(n) spacegreedy · hashing
An ad exchange sells blocks of impressions. A trading desk watches the price of one block each day, and it must buy on one day and sell on a later day.
The desk wants two numbers about the past. The first is the best profit that one purchase and one later sale could make. The second is in how many different ways that best profit could be made. A way is a pair of days, a purchase day and a later sale day.
Write best_trade_ways(prices).
prices[d] is the price of the block on day d. There are at least two days.buy < sell. Its profit is prices[sell] - prices[buy], which can be negative. The desk must make a trade.best be the largest profit of any trade.[best, ways], where ways is the number of pairs buy < sell with profit best.Input: prices = [1, 4, 1, 4, 2]
Output: [3, 3]The first table shows the best profit for a sale on each day.
| Day | Price | Lowest price before | Profit if sold today |
|---|---|---|---|
| 1 | 4 | 1 | 3 |
| 2 | 1 | 1 | 0 |
| 3 | 4 | 1 | 3 |
| 4 | 2 | 1 | 1 |
The second table counts the pairs for best = 3.
| Day | Price | Buy price needed | Earlier days with that price |
|---|---|---|---|
| 0 | 1 | -2 | 0 |
| 1 | 4 | 1 | 1 |
| 2 | 1 | -2 | 0 |
| 3 | 4 | 1 | 2 |
| 4 | 2 | -1 | 0 |
The best profit is 3. The table of the first pass shows it. Three pairs of days reach it: days (0, 1), (0, 3) and (2, 3). The second table counts them.
Input: prices = [5, 4, 3]
Output: [-1, 2]Prices only fall, so the least bad trade loses 1: days (0, 1) and (1, 2). There are 2 ways.
Input: prices = [7, 7]
Output: [0, 1]There is one pair of days, with profit 0.
2 ≤ prices.length ≤ 100,000 (days)1 ≤ prices[d] ≤ 1,000,000,000 (units)The number of ways can reach about 5 × 10^9, so it needs a 64-bit result.
Trying every pair of days costs about n × n / 2 steps, 5 × 10^9 at n = 100,000. Two passes cost about 2n steps. The first pass finds the best profit with a running minimum. The second pass counts pairs with a map from price to the number of earlier days with that price.