10. Best Time to Buy and Sell Stock
easyAsked at NubankFind the max profit from a single buy/sell over a price series — a one-pass sliding minimum that Nubank uses as an analog for FX/credit risk windowing.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
You are given an array prices where prices[i] is the price of an asset on day i. Return the maximum profit achievable from one buy and one later sell. If no profit is possible, return 0.
Constraints
1 <= prices.length <= 10^50 <= prices[i] <= 10^4
Examples
Example 1
prices = [7,1,5,3,6,4]5Example 2
prices = [7,6,4,3,1]0Approaches
1. Brute force all pairs
Try every (buy, sell) pair.
- Time
- O(n^2)
- Space
- O(1)
function maxProfit(p){ let m=0; for(let i=0;i<p.length;i++) for(let j=i+1;j<p.length;j++) m=Math.max(m,p[j]-p[i]); return m; }Tradeoff:
2. Single-pass min-tracker
Track the running minimum buy price; at each day compute profit-if-sold-today against the min so far.
- Time
- O(n)
- Space
- O(1)
function maxProfit(prices) {
let minBuy = Infinity, best = 0;
for (const price of prices) {
if (price < minBuy) minBuy = price;
else if (price - minBuy > best) best = price - minBuy;
}
return best;
}Tradeoff:
Nubank-specific tips
At Nubank, frame the sliding-min as risk-window state in a credit-card ledger — they want to see you can map a textbook DP into a money-domain stream.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Best Time to Buy and Sell Stock and other Nubank interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →