Maximize profit in buying and selling stocks with Rest condition

The price of a stock on each day is given in an array arr[] for N days, the task is to find the maximum profit that can be made by buying and selling the stocks in those days with conditions that the stock must be sold before buying again and stock cannot be bought on the next day of selling a stock. (i.e, rest for at least one day).
Examples: 
 

Input: arr[] = {2, 4, 5, 0, 2} 
Output:
Explanation: Buy at cost 2 and sell at cost 4, profit = 2. Buy at cost 0 and sell at cost 2, profit = 2. Total profit = 4.
Input: arr[] = {2, 0, 5, 1, 8} 
Output:
 

 

Approach : 
Consider three states: REST, HOLD and SOLD.
 

REST means not doing anything. 
HOLD means holding stock (bought a stock and have not sold). 
SOLD means state after selling the stock.



To reach the REST state, do nothing. 
To reach the HOLD state, buy the stock. 
To reach the SOLD state, sell the stock for which first there is a need to buy.
By the above actions, a transition diagram is made. 
 

By using this transition diagram the profit can be found out.
On ith day: 
 

  • rest[i] denotes maximum profit made by resting on day i. Since ith day is rest day, the stock might have been sold on (i-1)th day or might not have been sold. The value of rest[i] = max( rest[i-1], sold[i-1]).
  • hold[i] denotes maximum profit made by buying on ith day or by buying on some day before ith and resting on ith day. So, the value of hold[i] = max( hold[i-1], rest[i-1]+price[i]).
  • sold[i] denotes maximum profit by selling ith day. Stock must have been bought on some day before selling it on the ith day. Hence sold[i] = hold[i-1] + price[i]
     

Hence, the final answer will be the 
 

maximum of sold[n-1] and rest[n-1].

Below is the implementation of the above approach: 
 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above problem
#include <bits/stdc++.h>
using namespace std;
  
int maxProfit(int prices[], int n)
{
    // If there is only one day
    // for buying and selling
    // no profit can be made
    if (n <= 1)
        return 0;
  
    // Array to store Maxprofit by
    // resting on given day
    int rest[n] = { 0 };
  
    // Array to store Maxprofit by
    // buying or resting on the
    // given day
    int hold[n] = { 0 };
  
    // Array to store Maxprofit by
    // selling on given day
    int sold[n] = { 0 };
  
    // Initially there will 0 profit
    rest[0] = 0;
  
    // Buying on 1st day results
    // in negative profit
    hold[0] = -prices[0];
  
    // zero profit since selling
    // before buying isn't possible
    sold[0] = 0;
  
    for (int i = 1; i < n; i++) {
  
        // max of profit on (i-1)th
        // day by resting and profit
        // on (i-1)th day by selling.
        rest[i] = max(rest[i - 1],
                      sold[i - 1]);
  
        // max of profit by resting
        // on ith day and
        // buying on ith day.
        hold[i] = max(hold[i - 1],
                      rest[i - 1]
                          - prices[i]);
  
        // max of profit by selling
        // on ith day
        sold[i] = hold[i - 1] + prices[i];
    }
  
    // maxprofit
    return max(rest[n - 1],
               sold[n - 1]);
}
  
// Driver Code
int main()
{
    int price[] = { 2, 4,
                    5, 0, 2 };
    int n = sizeof(price)
            / sizeof(price[0]);
    cout << maxProfit(price, n)
         << endl;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above problem
class GFG{
  
static int maxProfit(int prices[], int n)
{
      
    // If there is only one day
    // for buying and selling
    // no profit can be made
    if (n <= 1)
        return 0;
  
    // Array to store Maxprofit by
    // resting on given day
    int rest[] = new int[n];
  
    // Array to store Maxprofit by
    // buying or resting on the
    // given day
    int hold[] = new int[9];
  
    // Array to store Maxprofit by
    // selling on given day
    int sold[] = new int[9];
  
    // Initially there will 0 profit
    rest[0] = 0;
  
    // Buying on 1st day results
    // in negative profit
    hold[0] = -prices[0];
  
    // Zero profit since selling
    // before buying isn't possible
    sold[0] = 0;
  
    for(int i = 1; i < n; i++)
    {
         
       // max of profit on (i-1)th
       // day by resting and profit
       // on (i-1)th day by selling.
       rest[i] = Math.max(rest[i - 1],
                          sold[i - 1]);
         
       // max of profit by resting
       // on ith day and
       // buying on ith day.
       hold[i] = Math.max(hold[i - 1], 
                          rest[i - 1] - 
                        prices[i]);
         
       // max of profit by selling
       // on ith day
       sold[i] = hold[i - 1] + prices[i];
    }
      
    // maxprofit
    return Math.max(rest[n - 1],
                    sold[n - 1]);
}
  
// Driver Code
public static void main(String[] args)
{
    int price[] = { 2, 4, 5, 0, 2 };
    int n = price.length;
      
    System.out.print(maxProfit(price, n) + "\n");
}
}
  
// This code is contributed by amal kumar choubey

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above problem 
using System;
  
class GFG{
      
static int maxProfit(int[] prices, int n) 
      
    // If there is only one day 
    // for buying and selling 
    // no profit can be made 
    if (n <= 1) 
        return 0; 
  
    // Array to store Maxprofit by 
    // resting on given day 
    int[] rest = new int[n]; 
  
    // Array to store Maxprofit by 
    // buying or resting on the 
    // given day 
    int[] hold = new int[9]; 
  
    // Array to store Maxprofit by 
    // selling on given day 
    int[] sold = new int[9]; 
  
    // Initially there will 0 profit 
    rest[0] = 0; 
  
    // Buying on 1st day results 
    // in negative profit 
    hold[0] = -prices[0]; 
  
    // Zero profit since selling 
    // before buying isn't possible 
    sold[0] = 0; 
  
    for(int i = 1; i < n; i++) 
    
          
        // max of profit on (i-1)th 
        // day by resting and profit 
        // on (i-1)th day by selling. 
        rest[i] = Math.Max(rest[i - 1], 
                           sold[i - 1]); 
              
        // max of profit by resting 
        // on ith day and 
        // buying on ith day. 
        hold[i] = Math.Max(hold[i - 1], 
                           rest[i - 1] - 
                         prices[i]); 
              
        // max of profit by selling 
        // on ith day 
        sold[i] = hold[i - 1] + prices[i]; 
    
      
    // maxprofit 
    return Math.Max(rest[n - 1], 
                    sold[n - 1]); 
  
// Driver code
static void Main() 
{
    int[] price = { 2, 4, 5, 0, 2 }; 
    int n = price.Length; 
  
    Console.WriteLine(maxProfit(price, n));
}
}
  
// This code is contributed by divyeshrabadiya07

chevron_right


Output:

4

Time Complexity: O(N) 
Auxillary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.