← Deloitte bank

Deloitte · Question 2 · Arrays

Best Time to Buy and Sell Stock

ArraysJavacode⏱ O(n)💾 O(1)
Service-based

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

  1. 1Track the lowest price so far.
  2. 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.
↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intmaxProfit(int[] prices)DEFINE min = prices[0],profit = 0for (int p : prices)min = Math.min(min, p)profit = Math.max(profit, p- min)RETURN profitDEFINE static voidmain(String[] args)System.out.println(maxProfit(newint[]{7, 1, 5, 3, 6, 4}))END
  • 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