思路:参考http://www.cnblogs.com/grandyang/p/4295761.html
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
if (prices.empty()) return 0;
if (k > int(prices.size())) return helper(prices);
vector<int> l(k+1, 0);
vector<int> g(k + 1, 0);
for (int i = 1; i<int(prices.size()); ++i)
{
int t = prices[i] - prices[i - 1];
for (int j = k; j >= 1; --j)
{
l[j] = max(g[j - 1] + max(t, 0), l[j] + t);
g[j] = max(l[j], g[j]);
}
}
return g[k];
}
int helper(vector<int> &prices)
{
int ans = 0;
for (int i = 1; i<int(prices.size()); ++i)
{
int t = prices[i]-prices[i - 1];
if (t > 0)
{
ans += t;
}
}
return ans;
}
};