```
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n=prices.size();
if (n<2)
return 0;
vector<vector<int>>T(k+1,vector<int>(n,0));
for (int i=1; i<=k; i++)
{
int maxdiff=-prices[0];
for (int j=1; j<n; j++)
{
T[i][j]=max(T[i][j-1], prices[j]+maxdiff);
maxdiff=max(maxdiff, T[i-1][j]-prices[j]);
}
}
return T[k][n-1];
}
};
```