Best Time to Buy and Sell Stock
Problem statement
The array prices holds a stock's price for each day: prices[i] is the price of one share on day i.
You can buy one share on one day and sell it on a later day, at most once. Return the most profit this single trade can make. If every possible trade loses money or makes nothing, return 0.
Function
maxProfit(prices: int[]) → intExamples
Example 1
prices = [7,1,5,3,6,4]return = 5Buy on day 1 at price 1 and sell on day 4 at price 6. The profit is 6 - 1 = 5.
The price 7 on day 0 is higher, but it comes before day 1, so it cannot be the sale for that purchase.
Example 2
prices = [9,7,7,4,2]return = 0The price never goes up from one day to a later day. Every trade would lose money or make nothing, so the answer is 0.
Example 3
prices = [3,9,1,4]return = 6The lowest price, 1, is on day 2. Buying there and selling on day 3 earns only 3. Buying on day 0 at 3 and selling on day 1 at 9 earns 6, which is the most.
Constraints
1 <= prices.length <= 10^50 <= prices[i] <= 10^4