Best Time to Buy and Sell Stock
Easy
Topics
You are given an array prices where prices[i] is the price of a stock on day i. Maximize profit by choosing one day to buy and a later day to sell. Return the max profit, or 0 if none.
Example 1
buy, then sell
Buy at 1 (day 1) and sell at 6 (day 4) for 5.
Bars are the daily prices, left to right.
Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy at 1, sell at 6.
Example 2
Prices never rise after a cheaper day, so no profitable trade exists and the answer is
0.Input: prices = [7,6,4,3,1] Output: 0
Constraints
- 1 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
You must buy before you sell, so for each day the best profit is that day’s price minus the cheapest price on any earlier day.
Sweeping left to right, keep the minimum price seen so far behind you and, at each day, ask "what if I sold today?"
Approach
- Track
minPrice(cheapest seen so far) andbestprofit. - For each price, update
best = max(best, price - minPrice). - Then update
minPrice = min(minPrice, price). - Return
best(0 if prices only fall).
Walkthrough
prices = [7, 1, 5, 3, 6, 4]
day 7: min=7 best=0
day 1: min=1 best=0
day 5: best=4 min=1
day 3: best=4
day 6: best=5 (6-1)
day 4: best=5 -> answer 5Complexity
- Time — O(n): one pass.
- Space — O(1): two scalars.
Common Pitfalls
- Update
bestbeforeminPriceeach day, otherwise you allow buying and selling on the same day for 0 which is harmless, but the order keeps the logic clear.
Full Solution — all languages
class Solution:
def maxProfit(self, nums):
best = 0
cheapest = float('inf')
for price in nums:
if price < cheapest:
cheapest = price
elif price - cheapest > best:
best = price - cheapest
return bestimport java.util.*;
class Solution {
public int maxProfit(int[] nums) {
int best = 0, cheapest = Integer.MAX_VALUE;
for (int price : nums) {
if (price < cheapest) cheapest = price;
else if (price - cheapest > best) best = price - cheapest;
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxProfit(vector<int>& nums) {
int best = 0, cheapest = INT_MAX;
for (int price : nums) {
if (price < cheapest) cheapest = price;
else if (price - cheapest > best) best = price - cheapest;
}
return best;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var maxProfit = function(nums) {
let best = 0, cheapest = Infinity;
for (const price of nums) {
if (price < cheapest) cheapest = price;
else if (price - cheapest > best) best = price - cheapest;
}
return best;
};