← L&T Mindtree bank

L&T Mindtree · Question 6 · Arrays

Best Time to Buy and Sell Stock

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

Problem

You are given an array of stock prices. Find the maximum profit from one buy and one sell transaction.

Approach

Track the minimum price and the best profit in a single pass.

Time O(n)Space O(1)

How it works

  1. 1Remember 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 minPrice =Integer.MAX_VALUE,maxProfit = 0for (int price :prices)minPrice =Math.min(minPrice, price)maxProfit =Math.max(maxProfit, price -minPrice)RETURN maxProfitDEFINE 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