- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Best Time to Buy and Sell Stock with Cooldown in C++
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 −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: 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; } }; main(){ Solution ob; vector<int> v = {1,2,3,0,2}; cout << (ob.maxProfit(v)); }
Input
[1,2,3,0,2]
Output
3
Advertisements