标签:
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
题解:
参考http://www.cnblogs.com/grandyang/p/4295761.html 和 http://blog.csdn.net/linhuanmars/article/details/23236995
class Solution { public: int solvemaxProfit(vector<int> prices) { int profit = 0; for(int i=0;i<prices.size()-1;i++) { if(prices[i+1]>prices[i]) profit += prices[i+1]-prices[i]; } return profit; } int maxProfit(int k, vector<int> &prices) { int n = prices.size(); if(n<=0) return 0; if(k>=n) return solvemaxProfit(prices); int global[k+1] = {0}; int local [k+1] = {0}; for(int i=0;i<n-1;i++) { int tmp = prices[i+1]-prices[i]; for(int j=k;j>=1;j--) { local[j] = max(global[j-1]+max(tmp, 0), local[j]+tmp); global[j] = max(local[j], global[j]); } } return global[k]; } };
[leetcode] Best Time to Buy and Sell Stock IV
标签:
原文地址:http://www.cnblogs.com/jiasaidongqi/p/4338934.html