The problem. You are given an array prices where prices[i] is a stock's price on day i. Choose one day to buy a share and a later day to sell it. Return the largest profit you can make — or 0 if no trade makes money.
Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5 buy on day 1 (price 1), sell on day 4 (price 6)
Input: prices = [7, 6, 4, 3, 1]
Output: 0 the price only falls, so don't tradeOrder matters: in the first example the highest price is 7, but it comes before the lowest price, so you can't buy at 1 and sell at 7. And if every trade loses money, you simply don't trade — the answer is never negative.
Free account
Sign up to read the rest of this lesson: 5 more sections, 3 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come