VOOZH about

URL: https://www.geeksforgeeks.org/dsa/all-variations-of-stock-problems/

⇱ Stock Buy and Sell - Complete Tutorial - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Stock Buy and Sell - Complete Tutorial

Last Updated : 8 Sep, 2025

Stock buy and sell problems are classic algorithmic challenges that focus on maximizing profit from trading stocks under various constraints. The primary goal is to determine the optimal times to buy and sell a stock to achieve the highest possible profit, considering the prices at different times.

πŸ‘ total_profit

These problems have many variations, including the allowance of multiple transactions, restrictions on the number of transactions, or the use of cooldown periods etc.

1. Best Time to Buy and Sell Stock (at most one transaction allowed)

Input: prices[] = {1, 3, 6, 9, 11} 
Output: 10
Explanation: Since the array is sorted in increasing order, we can make maximum profit by buying at price[0] and selling at price[n-1]

In the "Max one transaction allowed" problem, the goal is to maximize the profit by performing at most one transaction that is, one buy and one sell. To solve this, follow these steps:

  1. Identify the Lowest Buy Price: Traverse the list of prices and identify the minimum price up to the current index. This will be the best price to buy the stock.
  2. Calculate the Profit: At each price point, calculate the profit by subtracting the lowest buy price from the current price (i.e., profit = prices[i] - min_price).
  3. Track Maximum Profit: Keep track of the highest profit encountered during the traversal.

Refer Stock Buy and Sell – Max one Transaction Allowed for more.

2. Best Time to Buy and Sell Stock II (infinite transactions allowed)

Input: prices[] = {4, 2, 2, 2, 4}
Output: 2
Explanation: Buy the stock on day 3 and sell it on day 4 => 4 – 2 = 2
                       Maximum Profit  = 2


In the "Best Time to Buy and Sell Stock II" problem, where an unlimited number of transactions is allowed, the goal is to maximize profit by buying and selling the stock any number of times. Here's how to approach it:

  1. Identify Profitable Intervals: The key observation is that you can make a profit whenever the price increases from one day to the next. So, instead of focusing on buying at the lowest price and selling at the highest price, you simply buy at any price and sell at the next day's higher price.
  2. Accumulate Profit: Traverse through the array and whenever you notice that the price of the stock on day i+1 is greater than on day i, calculate the profit by prices[i+1] - prices[i], and add it to the total profit.

Refer Stock Buy and Sell – Multiple Transaction Allowed for more.

3. Best Time to Buy and Sell Stock III (at most two transactions allowed)

Input:   prices[] = [10, 22, 5, 75, 65, 80]
Output:  87
Explanation: Buy at 10, sell at 22, profit = 22 – 10 = 12
Buy at 5 and sell at 80, total profit = 12 + (80 – 5) = 87

In the "Best Time to Buy and Sell Stock III" problem, where at most two transactions are allowed, the goal is to maximize the profit by performing at most two buys and two sells. Here’s how to approach the problem:

1. Divide the Problem: Split it into two sub-problems:

  • Maximize profit from the first transaction (buy and sell).
  • Maximize profit from the second transaction after the first one.

2. Track Profits: Use two arrays:

  • first_buy[i]: Max profit with one transaction by day i.
  • second_buy[i]: Max profit with two transactions by day i.

3. Combine Results: The final profit is the sum of both transactions' profits.

Refer Stock Buy and Sell – Max 2 Transactions Allowed for more

4. Best Time to Buy and Sell Stock IV (at most k transactions allowed)

Input: prices = [12, 14, 17, 10, 14, 13, 12, 15], k = 3
Output: 12
Explanation: Buy on 1st day and at 12 and sell on 3rd day at 17. Then, again buy on 4th day at 10 and sell on 5th day at 14. Lastly, buy on 7th day at 12 and sell on 8th day at 15. Total profit = 5 + 4 + 3 = 12

In the "Best Time to Buy and Sell Stock IV" problem (at most k transactions allowed), the goal is to maximize profit by performing up to k buy-sell transactions. Here's how you can approach the problem:

1. Define States: Let dp[t][i] represent the maximum profit with t transactions by the end of day i.

2. State Transitions: If you buy on day j (where j < i), the profit will be the maximum profit from previous transactions plus the profit from selling at day i: dp[t][i] = max(dp[t][i-1], prices[i] - prices[j] + dp[t-1][j])

3. Optimization: Use a helper variable to store the maximum profit during the loop for each transaction to avoid redundant calculations and reduce time complexity.

4. Final Answer: The result is stored in dp[k][n-1] where k is the number of allowed transactions and n is the number of days.

Refer Stock Buy and Sell – At-most k Transactions Allowed for more

5. Best Time to Buy and Sell Stock V (with cooldown)

Input: arr[] = {3, 1, 6, 1, 2, 4}
Output: 7
Explanation: You first buy on day 2 and sell on day 3 then cool down, then again you buy on day 5 and then sell on day 6. Clearly, the total profit earned is (6-1) + (4-2) = 7, which is the maximum achievable profit.

In this variation of the "Best Time to Buy and Sell Stock" problem, you're allowed to buy and sell stocks multiple times, but after each sale, you must wait for a cooldown period of D days before you can buy again. Here's how you can approach the problem:

  1. Holding a stock (hold[i]): The maximum profit if we are holding a stock at the end of day i.
  2. Sold the stock (sold[i]): The maximum profit if we sold a stock on day i.
  3. Cooldown (cooldown[i]): The maximum profit if we are in cooldown (not holding or selling any stock).

Refer Best Time to Buy and Sell Stock V (with cooldown) for more

6. Best Time to Buy and Sell Stock VI (with transaction fee)

Input: arr[] = [6, 1, 7, 2, 8, 4], k = 2
Output: 8 1
Explanation: Buy the stock on day 2 and sell it on day 3 => 7 – 1 -2 = 4
Buy the stock on day 4 and sell it on day 5 => 8 – 2 – 2 = 4
Maximum Profit  = 4 + 4 = 8


In the "Best Time to Buy and Sell Stock VI (with Transaction Fee)" problem, we are given a list of stock prices arr[] and a transaction fee k. The goal is to maximize the profit by buying and selling stocks any number of times, but with a fixed transaction fee for each buy and sell action. Here's how you can approach the problem:

1. States:

  • hold[i]: Maximum profit if holding a stock on day i.
  • sold[i]: Maximum profit if not holding a stock (i.e., sold) on day i.

2. Recurrence Relations:

  • hold[i] = max(hold[i-1], sold[i-1] - arr[i]): Either continue holding or buy on day i.
  • sold[i] = max(sold[i-1], hold[i-1] + arr[i] - k): Either stay in sold state or sell on day i after paying the transaction fee k.

3. Final Result: Return sold[n-1], as it represents the max profit with no stock at the end.

Refer Best Time to Buy and Sell Stock VI (with transaction fee) for more

7. The Stock Span Problem

Input: arr[] = [10, 4, 5, 90, 120, 80]
Output: [1, 1, 2, 4, 5, 1]
Explanation: Traversing the given input span 10 is greater than equal to 10 and there are no more elements behind it so the span is 1, 4 is greater than equal to 4 and smaller than 10 so the span is 1, 5 is greater than equal to 4,5 and smaller than 10 so the span is 2, and so on. Hence the output will be 1 1 2 4 5 1.

The Stock Span Problem involves calculating the span of stock prices for each day. The span of a stock's price on a given day is the number of consecutive days (starting from that day and going backward) the price has been less than or equal to the current day's price. Here's how you can approach the problem:

Use a Stack:

  • For each price, pop from the stack while the top price is smaller than or equal to the current price.
  • Calculate span as the difference between current index and the index from the stack's top (or 0 if empty).
  • Push current index onto the stack

Refer The Stock Span Problem for more

8. Buy Maximum Stocks if i stocks can be bought on ith day

Input : price[] = [10, 7, 5, 8, 9], k = 50
Output: 8
Explanation: The customer can buy 1 stock on day 1 (cost 5), 2 stocks on day 2 (cost 7 each), and 3 stocks on day 3 (cost 8 each), for a total of 8 stocks, with 50 money.

In this problem, we are given the stock prices for N days, and the customer can buy at most i stocks on the i-th day. The goal is to maximize the number of stocks the customer can buy with an initial amount of k money. Here's how you can approach the problem:

  1. Sort Stock Prices: Sort the stock prices in ascending order to prioritize buying cheaper stocks first.
  2. Buy Stocks: For each day, buy up to i stocks (where i is the day index), deduct money, and stop when you can’t afford more.
  3. Greedy Approach: Start from the least expensive stocks and buy as many as possible with the available money.

Refer Buy Maximum Stocks if i stocks can be bought on i-th day for more

Comment