Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<climits>
- #include<algorithm>
- #include<cstring>
- #include<vector>
- using namespace std;
- int main()
- {
- int t; //test cases
- cin>>t;
- while(t--){
- int k,n;
- // k -> Atmost no. of transactions
- // n -> no. of days
- cin>>k>>n;
- vector<int> price(n);
- int dp[40][15][2] = {};
- for(int i=0;i<n;++i)
- cin>>price[i];
- dp[0][1][0] = -price[0];
- // Final maximum profit will get stored in ans.
- int ans = 0;
- for(int i=1;i<n;++i){ // i-> ith day
- int buy_sell_count = min(i/2+1,k); // buy_sell_count cannot exceed k because we are only allowed atmost k transactions
- for(int j=1;j<=buy_sell_count;++j){
- int mx0 = INT_MIN, mx1 = INT_MIN;
- for(int l=0;l<i;++l){
- mx0 = max(mx0, dp[l][j-1][1]); // dp[l][j-1][1] total max profit gained till selling(j-1)th transaction
- mx1 = max(mx1, dp[l][j][0]); // dp[l][j][0] total max profit gained till buying the jth transaction.
- }
- dp[i][j][0] = (mx0==INT_MIN)?INT_MIN:mx0-price[i];
- dp[i][j][1] = (mx1==INT_MIN)?INT_MIN:mx1+price[i];
- ans = max(ans, dp[i][j][1]);
- }
- }
- cout<<ans<<endl;
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment