121. Best Time to Buy and Sell Stock
easyAsked at CohereFind the maximum profit from a single buy-sell transaction. Cohere includes this because the running-minimum pattern mirrors how inference cost optimizers track cheapest-batch windows across fluctuating GPU pricing.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Source citations
Public interview reports confirming this problem appears in Cohere loops.
- Glassdoor (2025-Q4)— Cohere SWE phone-screen reports include this as a classic greedy warm-up.
- Blind (2025-09)— Mentioned by Cohere candidates alongside maximum subarray as standard easy-level prep.
Problem
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Constraints
1 <= prices.length <= 10^50 <= prices[i] <= 10^4
Examples
Example 1
prices = [7,1,5,3,6,4]5Explanation: Buy on day 2 (price=1), sell on day 5 (price=6). Profit = 6-1 = 5.
Example 2
prices = [7,6,4,3,1]0Explanation: Prices only decrease; no profitable transaction exists.
Approaches
1. Brute force
Try every pair (i, j) where i < j and track maximum prices[j] - prices[i].
- Time
- O(n²)
- Space
- O(1)
function maxProfit(prices) {
let max = 0;
for (let i = 0; i < prices.length; i++) {
for (let j = i + 1; j < prices.length; j++) {
max = Math.max(max, prices[j] - prices[i]);
}
}
return max;
}Tradeoff: Correct but O(n²) — too slow for 10^5 elements. Mention it only to establish the naive baseline.
2. Single pass with running minimum
Track the minimum price seen so far. At each day compute the profit if sold today, and update the global maximum.
- Time
- O(n)
- Space
- O(1)
function maxProfit(prices) {
let minPrice = Infinity;
let maxProfit = 0;
for (const price of prices) {
if (price < minPrice) {
minPrice = price;
} else {
maxProfit = Math.max(maxProfit, price - minPrice);
}
}
return maxProfit;
}Tradeoff: O(n) time, O(1) space — optimal. A single left-to-right sweep suffices because buy must precede sell.
Cohere-specific tips
Cohere engineers think in terms of streaming data and online algorithms. Frame your solution as an online algorithm: 'At each new price point I update my running minimum and check whether the current spread beats my best so far — I never need to look back.' This framing resonates strongly with teams building inference cost trackers and real-time model performance monitors.
Common mistakes
- Returning a negative profit — initialise maxProfit to 0, not -Infinity.
- Updating the minimum after computing the profit in the same iteration — leads to buying and selling on the same day.
- Using Infinity instead of prices[0] as the initial minimum — both work, but Infinity is cleaner because it avoids an off-by-one check.
- Forgetting the constraint that you must buy before you sell.
Follow-up questions
An interviewer at Cohere may pivot to one of these next:
- Best Time to Buy and Sell Stock II — unlimited transactions; greedy sum of all positive slopes.
- Best Time to Buy and Sell Stock with Cooldown — dynamic programming with state machine.
- How would you solve this if prices arrived in a real-time stream?
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
FAQ
Why doesn't this need dynamic programming?
Because there is only one transaction. The optimal buy day is always the minimum price before the optimal sell day, so a greedy single pass suffices.
What if all prices are equal?
Every spread is 0, so maxProfit stays 0 — correct, since no profit is possible.
Can you adapt this for a sliding window of k days?
Yes — maintain a deque of local minima within the window. This becomes a monotonic queue problem.
Practice these live with InterviewChamp.AI
Drill Best Time to Buy and Sell Stock and other Cohere interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →