给出每天的价格,求最大利润。
I 一次买进卖出
int maxProfit(vector<int>& prices) {
int profit = 0, max_profit = 0;
for (int i = 1; i < prices.size(); i++){
int diff = prices[i] - prices[i - 1];
if (profit >= 0)
profit += diff;
else
profit = diff;
if (profit > max_profit)
max_profit = profit;
}
return max_profit;
}
II 无限次买进卖出
int maxProfit(vector<int>& prices) {
int profit = 0;
for (int i = 1; i<prices.size();i++){
int temp = prices[i] - prices[i - 1];
if (temp>0) profit += temp;
}
return profit;
}
III 最多两次买进卖出
int maxProfit(vector<int>& prices) {
int n = prices.size();
int global[3] = { 0 }, local[3] = { 0 };
for (int i = 1; i<n; i++){
for (int j = 2; j >= 1; j--){
int diff = prices[i] - prices[i - 1];
local[j] = max(global[j - 1] + max(diff, 0), local[j] + diff);
global[j] = max(global[j], local[j]);
}
}
return global[2];
}
IV 最多K次买进卖出
int maxProfit(int k, vector<int>& prices) {
int n = prices.size();
if (k >= n - 1) return maxProfitlarge(prices);
int global[k + 1] = { 0 }, local[k + 1] = { 0 };
for (int i = 1; i<n; i++){
for (int j = k; j >= 1; j--){
int diff = prices[i] - prices[i - 1];
local[j] = max(global[j - 1] + max(diff, 0), local[j] + diff);
global[j] = max(global[j], local[j]);
}
}
return global[k];
}
int maxProfitlarge(vector<int>& prices) {
int profit = 0;
for (int i = 1; i<prices.size(); i++){
int temp = prices[i] - prices[i - 1];
if (temp>0) profit += temp;
}
return profit;
}
GitHub-Leetcode:https://github.com/wenwu313/LeetCode
解题思路四:http://www.cnblogs.com/grandyang/p/4295761.html
解题思路三: http://www.cnblogs.com/grandyang/p/4281975.html