← Google bank

Google · Question 2 · Arrays

Best Time to Buy and Sell Stock

ArraysPythoncode⏱ O(n)💾 O(1)
Product-based

Problem

Given a list prices where prices[i] is the stock price on day i, find the maximum profit from one buy and one sell.

Approach

Track minimum price and max profit while traversing once.

Time O(n)Space O(1)

How it works

  1. 1Initialize min_price to infinity and max_profit to zero.
  2. 2Update min_price to the lowest price seen so far.
  3. 3Compute the profit for each price and update max_profit.
  4. 4Return the max profit found.

Sample input / output

Input:
6
7 1 5 3 6 4
Output:
5

Constraints

1 <= prices.length <= 10^5; 0 <= prices[i] <= 10^4.

Solution — read it, then walk it

Time O(n)Space O(1)Loops 1Branches 1Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyesnoSTARTpricesmin_price = float('inf')max_profit = 0for price in pricesmin_price = min(min_price,price)max_profit =max(max_profit, price -min_price)RETURN max_profitDEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)n = int(next(it))prices = [int(next(it)) for_ in range(n)]print(maxProfit(prices))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/17

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