Deloitte · Question 2 · Arrays
Best Time to Buy and Sell Stock
Problem
Find the maximum profit from a single buy and sell action. Track the minimum price and compute profit differences.
Approach
Track the minimum price and the best profit in a single pass.
Time O(n)Space O(1)
How it works
- 1Track the lowest price so far.
- 2Sell-profit today updates the best.
Sample input / output
Input: prices = [7, 1, 5, 3, 6, 4] Output: 5
Constraints
1 <= prices.length <= 10^5.
Solution — read it, then walk it
Time O(n)Space O(1)Loops 1Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/11
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits