10. Best Time to Buy and Sell Stock
easyAsked at LINEFind the maximum profit from one buy and one sell — LINE uses this to see if you spot the running-minimum trick, the same primitive behind their payment-reconciliation min-balance scan.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array prices where prices[i] is the price of a given stock on day i, return the maximum profit you can achieve from buying on one day and selling on a later day. Return 0 if no profit is possible.
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 pairs
Try every buy day i and every sell day j > i, track the max difference.
- Time
- O(n^2)
- Space
- O(1)
let best=0;
for(let i=0;i<prices.length;i++)
for(let j=i+1;j<prices.length;j++)
best=Math.max(best,prices[j]-prices[i]);
return best;Tradeoff:
2. Single pass running minimum
Track the lowest price seen so far while sweeping left to right. Each day's candidate profit is current price minus running minimum.
- Time
- O(n)
- Space
- O(1)
function maxProfit(prices) {
let minP = Infinity, best = 0;
for (const p of prices) {
if (p < minP) minP = p;
else if (p - minP > best) best = p - minP;
}
return best;
}Tradeoff:
LINE-specific tips
At LINE, mention that this running-min sweep is the same one-pass shape they use when scanning a LINE Pay wallet ledger for minimum daily balance — payment-integration framing wins points.
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 LINE interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →