Best Time to Buy and Sell Stock — Algorithm Visualization & Coding Challenge

Choose Your Learning Path

How would you like to learn today?
Visualize algorithms in real time, explore them step by step, or challenge yourself with a test.Choose a path to focus—or scroll down to preview all options.

🧠 Active Learning

Visualize the algorithm step-by-step with interactive animations in real time.

📖 Passive Learning

Read the full explanation, examples, and starter code at your own pace.

🎯 Challenge Mode

Drag and arrange the algorithm steps in the correct execution order.

🧠 Select Active to activate

JUMP INTO VISUALIZATION
Watch algorithms run step by step.

Follow every state change, comparison, and transformation as the execution unfolds in real time.

📖 Select Passive to activate

Understanding Best Time to Buy and Sell Stock
Detailed explanation and reference materials
Problem Overview

Maximum Profit from Stock Trading

Objective:
To determine the maximum profit that can be achieved from buying and selling stock on given days, where the price of the stock is provided as an array.


Steps:

1. Initialize Variables:

  • maxProfit: This variable will store the maximum profit encountered so far.
  • minSoFar: This variable represents the minimum stock price encountered up to the current day. Initialize it to the stock price on the first day.

2. Iterate Through the Array:

  • Use a for loop to iterate through the array of stock prices.

    • For each day, calculate the potential profit by subtracting minSoFar from the current stock price.
    • If this potential profit is greater than the current maxProfit, update maxProfit with the new potential profit.

    Additionally, update minSoFar to be the minimum of its current value and the current stock price. This ensures that you always have the lowest price encountered up to the current day.


3. Return the Result:

  • After iterating through the entire array, the final value of maxProfit will hold the maximum profit achievable by buying and selling the stock.

Test Cases:

Test Case 1:

Input:
prices = [7, 1, 5, 3, 6, 4]

Output:
Maximum Profit = 5
Explanation:

  • Buy on day 2 (price = 1), sell on day 5 (price = 6), profit = 6 - 1 = 5.

Test Case 2:

Input:
prices = [7, 6, 4, 3, 1]

Output:
Maximum Profit = 0
Explanation:

  • No transaction is made as prices are decreasing. No profit can be achieved.

Test Case 3:

Input:
prices = [1, 2, 3, 4, 5]

Output:
Maximum Profit = 4
Explanation:

  • Buy on day 1 (price = 1), sell on day 5 (price = 5), profit = 5 - 1 = 4.

Test Case 4:

Input:
prices = [3, 2, 6, 5, 0, 3]

Output:
Maximum Profit = 4
Explanation:

  • Buy on day 2 (price = 2), sell on day 3 (price = 6), profit = 6 - 2 = 4.

Code Example:

python
def maxProfit(prices):
    maxProfit = 0
    minSoFar = prices[0]
    
    for price in prices:
        maxProfit = max(maxProfit, price - minSoFar)
        minSoFar = min(minSoFar, price)
    
    return maxProfit
— Written by Saurabh Patil • B.Tech CSE • Software Developer

Categories
array
java
Reference Link
https://leetcode.com/problems/pascals-triangle/description/

Loading component...

Starter Code
Test, modify, or copy the starter code. Click "Visualize" to import into the canvas.
Java
Output:
Understood Algorithm, Test Me now 🎮

🎯 Select Challenge to activate

🧠 Logic Puzzle
Think & Arrange, Don't Just Copy-Paste

Drag and arrange the algorithm steps in the correct execution order instead of spending time typing code letter by letter.

Arrange the Algorithm Correctly 🧩

The algorithm is divided into three logical parts. Carefully rearrange each section in the correct order to form a complete and valid solution.

Understand Below Algorithm

Don't Know Current Algorithm ?  

Green text means the instruction is placed in the correct position.

Red text means the instruction is in the wrong position.

Block Colors

Instructions with the same background color indicate particular blocks start and end.

A tick mark means the instruction is correct and locked.

🔒 Locked steps cannot be moved. Only unlocked steps are draggable.

🔊 Enable sound for swap feedback and completion effects.

DrawToCode — Visualize, Practice & Master Algorithms

Learn data structures and algorithms through interactive visualizations. Practice coding problems, track your progress, and understand concepts deeply.

EmailLinkedInTwitterInstagramGitHub
© 2026 DrawToCode. All rights reserved.