← Accenture bank

Accenture · Question 2 · Arrays

Best Time to Buy and Sell Stock

ArraysC++code⏱ O(n)💾 O(1)
Service-based

Problem

Given an array prices, find the maximum profit from one buy and one sell.

Approach

Track minimum price and maximum profit while iterating once.

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 1Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeatSTARTinclude <iostream>include <vector>include <algorithm>include <climits>using namespace stdDEFINEmaxProfit(vector<int>&prices)DEFINE minPrice = INT_MAXDEFINE maxProfit = 0for (int price :prices)minPrice =std::min(minPrice, price)maxProfit =std::max(maxProfit, price -minPrice)RETURN maxProfitDEFINE main()vector<int> prices = {7, 1,5, 3, 6, 4}cout << maxProfit(prices)<< endlRETURN 0END
  • 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