DSA Visualizer · 25 visualizationsBest Time to Buy and Sell Stock
Arrays & Hashing
Two SumValid AnagramContains DuplicateGroup AnagramsTop K Frequent ElementsProduct of Array Except SelfLongest Consecutive SequenceStack
Valid ParenthesesBinary Search
Binary SearchTrees & BFS
Binary Tree Level OrderGraphs
Number of IslandsTrees
Invert Binary TreeEasySliding Window
Best Time to Buy and Sell Stock
You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy and a different day in the future to sell. Return the maximum profit, or 0 if no profit is possible.
The step-through player is coming for this one. Two Sum has the full animation today; the rest are being authored in the admin.
Pythontime O(n) · space O(1)
def maxProfit(prices: list[int]) -> int:
minPrice, maxProfit = float('inf'), 0
for p in prices:
minPrice = min(minPrice, p)
maxProfit = max(maxProfit, p - minPrice)
return maxProfitTwo Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free
Watch the video walkthrough