aj30

Untitled

Dec 27th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include<iostream>
  2. #include<climits>
  3. #include<algorithm>
  4. #include<cstring>
  5. #include<vector>
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10.     int t; //test cases
  11.     cin>>t;
  12.     while(t--){
  13.         int k,n;
  14.         // k -> Atmost no. of transactions
  15.         // n -> no. of days
  16.         cin>>k>>n;
  17.         vector<int> price(n);
  18.         int dp[40][15][2] = {};
  19.         for(int i=0;i<n;++i)
  20.             cin>>price[i];
  21.         dp[0][1][0] = -price[0];
  22.        
  23.         // Final maximum profit will get stored in ans.
  24.         int ans = 0;
  25.  
  26.         for(int i=1;i<n;++i){ // i-> ith day
  27.             int buy_sell_count = min(i/2+1,k); // buy_sell_count cannot exceed k because we are only allowed atmost k transactions
  28.             for(int j=1;j<=buy_sell_count;++j){
  29.                 int mx0 = INT_MIN, mx1 = INT_MIN;
  30.                 for(int l=0;l<i;++l){
  31.                     mx0 = max(mx0, dp[l][j-1][1]); // dp[l][j-1][1] total max profit gained till selling(j-1)th transaction
  32.                     mx1 = max(mx1, dp[l][j][0]); // dp[l][j][0] total max profit gained till buying the jth transaction.
  33.                 }
  34.                 dp[i][j][0] = (mx0==INT_MIN)?INT_MIN:mx0-price[i];
  35.                 dp[i][j][1] = (mx1==INT_MIN)?INT_MIN:mx1+price[i];
  36.                 ans = max(ans, dp[i][j][1]);
  37.             }
  38.         }    
  39.         cout<<ans<<endl;
  40.     }
  41.     return 0;
  42. }
Add Comment
Please, Sign In to add comment