Continue learning
Practice related DSA questions in the same topic.
Buy once and sell on a later day. Return the largest profit, or zero if trading cannot help.
Buy once and sell on a later day. Return the largest profit, or zero if trading cannot help.
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 bestTest today's sale using the lowest earlier price 1001.
Test today's sale using the lowest earlier price 1001.
A shopkeeper compares today’s offer with the cheapest purchase already seen.
Use the lowest earlier price to price a sale today.
O(n) time · O(1) auxiliary space
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
Subtracting prices from dates in reverse order permits time travel.
How does a transaction fee change the calculation?