Skip to content
Related Articles

Related Articles

Improve Article

Maximize profit in buying and selling stocks with Rest condition

  • Difficulty Level : Hard
  • Last Updated : 26 May, 2021

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++




// 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;
}

Java




// 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

Python3




# Python3 program for the above problem
def maxProfit(prices, 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
    rest = [0] * n
 
    # Array to store Maxprofit by
    # buying or resting on the
    # given day
    hold = [0] * n
 
    # Array to store Maxprofit by
    # selling on given day
    sold = [0] * n
 
    # 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 i in range(1, n):
 
        # 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
price = [ 2, 4, 5, 0, 2 ]
n = len(price)
 
print(maxProfit(price, n))
 
# This code is contributed by avanitrachhadiya2155

C#




// 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

Javascript




<script>
 
// JavaScript program for the above problem
 
function maxProfit( prices,  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
        let rest = [];
    for(let k = 0;k<n;k++)
         rest.push(0);
 
    // Array to store Maxprofit by
    // buying or resting on the
    // given day
        let hold = [];
    for(let k = 0;k<n;k++)
         hold.push(0);
 
    // Array to store Maxprofit by
    // selling on given day
    let sold = [];
    for(let k = 0;k<n;k++)
         sold.push(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 (let 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
let price = [ 2, 4,
                    5, 0, 2 ];
let n = price.length;
document.write( maxProfit(price, n),'<br>');
 
 
</script>
Output:
4

Time Complexity: O(N) 
Auxiliary 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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :