Comic Book Flip

EasygreedyAlso known as Best Time to Buy and Sell Stock

A collector's shop puts a new price on a rare comic every morning. You wrote the prices down over the past few weeks. Looking back, you wonder: if you had bought one copy on some day and sold it to another collector for that day's shop price on a later day, what is the most you could have made?

You must buy before you sell, and you can only do it once. If every possible deal loses money, you would simply not have bought.

Your task

Write bestFlip(prices). prices[i] is the price on day i. Return the largest value of prices[sell] - prices[buy] over all pairs of days with buy < sell.

If no pair makes a profit, or there are fewer than two days, return 0.

bestFlip(prices: int[]) → int

Examples

Example 1
Input
prices = [30, 22, 41, 18, 35, 27]
Output
19
Why

Buy on day 1 at 22 and sell on day 2 at 41 for a profit of 19. Buying at the lowest price, 18 on day 3, only gets you 35 - 18 = 17. The cheapest day is not always the best day to buy.

Example 2
Input
prices = [50, 44, 39, 31]
Output
0
Why

The price only falls. Every deal would lose money, so you do not trade and the answer is 0.

Example 3
Input
prices = [12, 40, 5, 9]
Output
28
Why

The highest price is 40 and the lowest is 5, but 5 comes after 40, so you cannot buy at 5 and sell at 40. The best real deal is 40 - 12 = 28.

Constraints

  • 0 ≤ prices.length ≤ 100,000
  • 0 ≤ prices[i] ≤ 100,000
Start with brute force

Try every buying day with every later selling day and keep the largest difference.

That is about n²/2 pairs. With 100,000 days it is roughly 5 billion pairs. Each selling day rescans all the earlier days to find the cheapest one, even though that answer only changes by one day at a time.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code