Best Time to Buy and Sell Stock with Cooldown in C++

C++Server Side ProgrammingProgramming

Suppose we have an array for which the ith element is the price of a given stock on the day i. We have to design an algorithm to find the maximum profit. We may complete as many transactions as we want (So, buy one and sell one share of the stock multiple times). But we have to follow these rules −

  • We may not engage in multiple transactions at the same time (So, we must sell the stock before you buy again).
  • After we sell our stock, we cannot buy stock on next day. (So cool down 1 day)

If the input is like [1,2,3,0,2], then the output will be 3, the sequence is like [buy, sell, cooldown, buy, sell]

To solve this, we will follow these steps −

  • endWithSell := 0, endWithBuy := -ve infinity, prevBuy := 0 and prevSell := 0
  • for i := 0 to size of the given array
    • prevBuy := endWithBuy
    • endWithBuy := max of endWithBuy and prevSell – Arr[i]
    • prevSell := endWithSell
    • endWithSell := max of endWithSell and prevBuy + Arr[i]
  • return endWithSell

Let us see the following implementation to get better understanding −


 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   int maxProfit(vector<int>& p) {
      int endWithSell = 0;
      int endWithBuy = INT_MIN;
      int prevBuy =0, prevSell = 0;
      for(int i =0;i<p.size();i++){
         prevBuy = endWithBuy;
         endWithBuy = max(endWithBuy,prevSell - p[i]);
         prevSell = endWithSell;
         endWithSell = max(endWithSell, prevBuy + p[i]);
      return endWithSell;
   Solution ob;
   vector<int> v = {1,2,3,0,2};
   cout << (ob.maxProfit(v));




Published on 05-Feb-2020 15:10:04