Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- void getMaximumProfitWithTransactions(int level, int transactionState, int transactions, int currProfit, int &maxProfit, vector<int> &prices){
- if(level >= prices.size()){
- maxProfit = max(maxProfit, currProfit);
- return;
- }
- //levels - stocks on each day
- /*
- options -
- transactionState = 0; buy
- transactionState = 1; sell
- don't do anything
- */
- //only start a new transaction if transaction is closed and transactions > 0
- if(transactionState == 0 && transactions > 0){
- getMaximumProfitWithTransactions(level + 1, 1, transactions, currProfit - prices[level], maxProfit, prices);
- }
- //only call if transaction is open
- if(transactionState == 1){
- getMaximumProfitWithTransactions(level + 1, 0, transactions - 1, currProfit + prices[level], maxProfit, prices);
- }
- getMaximumProfitWithTransactions(level + 1, transactionState, transactions, currProfit, maxProfit, prices);
- }
- int getMaximumProfitWithTransactionsMemo(int level, int transactionState, int transactions, vector<int> &prices, vector<vector<vector<int> > > &memo){
- //base case
- if(level >= prices.size()){
- return 0;
- }
- //memo check
- if(memo[level][transactionState][transactions] != -1){
- return memo[level][transactionState][transactions];
- }
- int bought = 0, sold = 0, na = 0;
- //buy
- if(transactionState == 0 && transactions > 0){
- bought = getMaximumProfitWithTransactionsMemo(level + 1, 1, transactions, prices, memo) - prices[level];
- }
- if(transactionState == 1){
- sold = getMaximumProfitWithTransactionsMemo(level + 1, 0, transactions - 1, prices, memo) + prices[level];
- }
- na = getMaximumProfitWithTransactionsMemo(level + 1, transactionState, transactions, prices, memo);
- return memo[level][transactionState][transactions] = max(na, max(sold, bought));
- }
- int main() {
- // your code goes here
- int n;
- cin >> n;
- vector<int> prices(n);
- for(int i = 0; i < n; i++){
- cin >> prices[i];
- }
- /*
- Recursive call
- int maxProfit = 0;
- getMaximumProfitWithTransactions(0, 0, 2, 0, maxProfit, prices);
- cout << maxProfit << '\n';
- */
- vector<vector<vector<int> > > memo(prices.size(), vector<vector<int> >(2, vector<int>(3, -1))) ;
- cout << getMaximumProfitWithTransactionsMemo(0, 0, 2, prices, memo) << '\n';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement