Best Time to Buy and Sell Stock
EasyYou are given an array prices where prices[i] is the price of a stock on day i. You want to maximize your profit by choosing a single day to buy and a different day to sell. Return the maximum profit. If no profit is possible, return 0.
Examples
| Input | Output |
|---|---|
| prices = [7,1,5,3,6,4] | 5 |
| prices = [7,6,4,3,1] | 0 |
Python Solution
def max_profit(prices: list[int]) -> int:
min_price = float("inf")
max_profit = 0
for p in prices:
min_price = min(min_price, p)
max_profit = max(max_profit, p - min_price)
return max_profitJavaScript Solution
function maxProfit(prices) {
let minPrice = Infinity, maxProfit = 0;
for (const p of prices) {
minPrice = Math.min(minPrice, p);
maxProfit = Math.max(maxProfit, p - minPrice);
}
return maxProfit;
}Step-by-Step Explanation
- Track the minimum price seen so far.
- At each day, profit = price - min_price. Track the maximum profit.
Complexity Analysis
| Time | O(n) |
| Space | O(1) |
Tags
ArrayDynamic Programming
Related Problems
Related Tools
All Problems
Two SumReverse a StringPalindrome CheckFizzBuzzBinary SearchReverse Linked ListMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Remove Duplicates from Sorted ArrayNth Fibonacci NumberValid AnagramFirst Unique CharacterClimbing StairsRoman to IntegerContains DuplicateMove ZeroesIntersection of Two ArraysLongest Common Prefix