Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int maxProfit(int k, vector<int>& prices) {
- auto s=prices.size();
- if(s<=1)
- return 0;
- if(2*k>=s)
- {
- int result=0;
- for(int i=1;i<s;++i)
- {
- auto t=prices[i]-prices[i-1];
- if(t>0)
- result+=t;
- }
- return result;
- }
- vector<vector<int>> dp(k+1,vector<int>(s,0));
- for(int i=1;i<=k;++i)
- {
- int buy=dp[i-1][0]-prices[0];
- for(int j=1;j<s;++j)
- {
- dp[i][j]=max(dp[i][j-1],prices[j]+buy);
- buy=max(buy,dp[i-1][j]-prices[j]);
- }
- }
- return dp[k][s-1];
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement