Best Time to Buy and Sell Stock
You're given an array prices, where prices[i] holds a stock's price on day i. You may buy the stock on exactly one day and sell it on a later day. Work out the largest profit achievable from this single buy-then-sell transaction, returning 0 if no profitable trade is possible.
Input Format
Implement maxProfit(prices). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 ยท Run Sample
Input
prices = [7,1,5,3,6,4] Output
5 Example 2
Input
prices = [7,6,4,3,1] Output
0 Constraints
- 1 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^4
Test Cases (2)
Case 1
Args: [[7,1,5,3,6,4]]
Expected: 5
Case 2
Args: [[7,6,4,3,1]]
Expected: 0
Topics
Track the minimum price seen so far as you iterate. At each step, compute the profit if you sold today and update the maximum profit accordingly.
function maxProfit(prices) {
let minPrice = Infinity;
let maxProfit = 0;
for (const price of prices) {
minPrice = Math.min(minPrice, price);
maxProfit = Math.max(maxProfit, price - minPrice);
}
return maxProfit;
}Time: O(n) Space: O(1)
Saved in this browser only. Private to you.