Best Time to Buy and Sell Stock
Problem statement
You are given an array prices, where prices[i] is the price of one share of a stock on day i.
You may make at most one trade: buy one share on one day, then sell it on a later day. Return the largest profit you can make. If no trade makes money, return 0.
Function
maxProfit(prices: int[]) → intExamples
Example 1
prices = [7,1,5,3,6,4]return = 5Buy on day 1, when the price is 1, and sell on day 4, when the price is 6. The profit is 6 - 1 = 5.
The price 7 on day 0 is higher, but it comes before day 1, so you cannot sell there after buying at 1.
Example 2
prices = [7,6,4,3,1]return = 0The price falls every day, so every possible trade loses money. The best choice is not to trade, which gives 0.
Example 3
prices = [2,4,1]return = 2The lowest price, 1, is on the last day, so there is no later day to sell it. The best trade is to buy at 2 on day 0 and sell at 4 on day 1, for a profit of 2.
Constraints
1 <= prices.length <= 10^50 <= prices[i] <= 10^4