← PayPal bank

PayPal · Question 2 · Arrays

Best Time to Buy and Sell Stock

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

Problem

Given an array where the i-th element is the price of a stock on day i, find the maximum profit by choosing a single day to buy and a single day to sell.

Approach

Track the minimum price so far and calculate max profit.

Time O(n)Space O(1)

How it works

  1. 1Track the lowest price seen.
  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 1Branches 2Returns 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_VALUEDEFINE maxProfit = 0for (int price :prices)if (price < minPrice)minPrice = priceelse if (price -minPrice > maxProfit)maxProfit = price …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/12

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