Comic Book Flip

EasygreedyAlso known as Best Time to Buy and Sell Stock

A collector's shop reprices a rare comic every morning, and you have written down the prices for the past few weeks. Had you bought one copy on some day and sold it for the shop's price on a later day, what is the most you could have made?

You buy before you sell, and only once. If every deal loses money, you would not have bought at all.

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

Buying on day 1 at 22 and selling on day 2 at 41 gives a profit of 19. Buying at the lowest price, 18 on day 3, only gives 35 - 18 = 17 at best, so 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, so every deal loses money. The best choice is not to 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 5, but 5 comes after 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: roughly 5 billion for 100,000 days. Each selling day rescans all earlier days for the cheapest, though that answer changes by only 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