Workspace Best Time To Buy And Sell Stock
0d
DSA Problem Sheet

Best Time to Buy and Sell Stock

Buy once and sell on a later day. Return the largest profit, or zero if trading cannot help.

EXECUTION LAB

Buy once and sell on a later day. Return the largest profit, or zero if trading cannot help.

Input and constraints
  • Each value must be nonnegative.
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
best = 0
low = 1001
i = 0
while (i < len(values)):
best = max(best, (values[i] - low))
low = min(low, values[i])
i = (i + 1)
return best

Visualizer

Step 1 of 6
08i
13
26
32
49

Inspect the current state

Test today's sale using the lowest earlier price 1001.

Variable watch

i 0best 0low 1001

Step explanation

Test today's sale using the lowest earlier price 1001.

comparisons 1reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(1) space

Worked explanation

A shopkeeper compares today’s offer with the cheapest purchase already seen.

Guided solution

Use the lowest earlier price to price a sale today.

O(n) time · O(1) auxiliary space

Examples

Worked example · {"values":[8,3,6,2,9],"target":0} ⇒ 7

Edge case 1 · {"values":[],"target":0} ⇒ 0

Edge case 2 · {"values":[6,3,1],"target":0} ⇒ 0

Progressive hints

Hint 1A shopkeeper compares today’s offer with the cheapest purchase already seen.
Hint 2Use the lowest earlier price to price a sale today.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Subtracting prices from dates in reverse order permits time travel.

Interview follow-up

How does a transaction fee change the calculation?