Tutorialspoint
Problem
Solution
Submissions

Best Time to Buy and Sell Stock III

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15
Problem 27: Best Time to Buy and Sell Stock III

Write a C program to find the maximum profit you can achieve from buying and selling stocks. You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete at most two transactions. Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Example 1
  • Input: prices = [3,3,5,0,0,3,1,4]
  • Output: 6
  • Explanation:
    • Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
    • Buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
    • Total profit = 3 + 3 = 6.
    • This uses exactly 2 transactions and gives maximum profit.
Example 2
  • Input: prices = [1,2,3,4,5]
  • Output: 4
  • Explanation:
    • Buy on day 1 (price = 1) and sell on day 2 (price = 2), profit = 2-1 = 1.
    • Buy on day 2 (price = 2) and sell on day 5 (price = 5), profit = 5-2 = 3.
    • Total profit = 1 + 3 = 4.
    • You can also buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 4.
Constraints
  • 1 ≤ prices.length ≤ 10^5
  • 0 ≤ prices[i] ≤ 10^5
  • You can complete at most 2 transactions
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysNumberWalmartD. E. Shaw
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use state machine approach with four states for two transactions
  • Track buy1, sell1, buy2, sell2 for maximum profit at each state
  • buy1: maximum profit after first buy
  • sell1: maximum profit after first sell
  • buy2: maximum profit after second buy
  • sell2: maximum profit after second sell
  • Update states in single pass through prices array

Steps to solve by this approach:

 Step 1: Initialize four state variables for tracking profit at each transaction state
 Step 2: buy1 represents maximum profit after first purchase (negative value initially)
 Step 3: sell1 represents maximum profit after first sale
 Step 4: buy2 represents maximum profit after second purchase
 Step 5: sell2 represents maximum profit after second sale (final answer)
 Step 6: For each day, update all states considering current stock price
 Step 7: Return sell2 as it represents maximum profit after completing at most 2 transactions

Submitted Code :