Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. class Solution {
  2. public:
  3. int maxProfit(int k, vector<int>& prices) {
  4. auto s=prices.size();
  5. if(s<=1)
  6. return 0;
  7.  
  8. if(2*k>=s)
  9. {
  10. int result=0;
  11. for(int i=1;i<s;++i)
  12. {
  13. auto t=prices[i]-prices[i-1];
  14. if(t>0)
  15. result+=t;
  16. }
  17. return result;
  18. }
  19. vector<vector<int>> dp(k+1,vector<int>(s,0));
  20.  
  21. for(int i=1;i<=k;++i)
  22. {
  23. int buy=dp[i-1][0]-prices[0];
  24. for(int j=1;j<s;++j)
  25. {
  26. dp[i][j]=max(dp[i][j-1],prices[j]+buy);
  27. buy=max(buy,dp[i-1][j]-prices[j]);
  28. }
  29. }
  30. return dp[k][s-1];
  31. }
  32. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement