leetcode 123. Best Time to Buy and Sell Stock III
既是dp(组合,先卖后买,先买后卖,需要比较) 又是贪心(每一单个操作最优,即是全局最优)
public class Solution {
public int maxProfit(int[] prices) {
// these four variables represent your profit after executing corresponding transaction
// in the beginning, your profit is 0.
// when you buy a stock ,the profit will be deducted of the price of stock.
int firstBuy = Integer.MIN_VALUE, firstSell = 0;
int secondBuy = Integer.MIN_VALUE, secondSell = 0;
for (int curPrice : prices) {
if (firstBuy < -curPrice) firstBuy = -curPrice; // the max profit after you buy first stock
if (firstSell < firstBuy + curPrice) firstSell = firstBuy + curPrice; // the max profit after you sell it
if (secondBuy < firstSell - curPrice) secondBuy = firstSell - curPrice; // the max profit after you buy the second stock
if (secondSell < secondBuy + curPrice) secondSell = secondBuy + curPrice; // the max profit after you sell the second stock
}
return secondSell; // secondSell will be the max profit after passing the prices
}
}
下面这种方法 dp 基本上绝大部分问题都可以化为dp问题
class Solution {
public:
int maxProfit(vector<int> &prices) {
// f[k, ii] represents the max profit up until prices[ii] (Note: NOT ending with prices[ii]) using at most k transactions.
// f[k, ii] = max(f[k, ii-1], prices[ii] - prices[jj] + f[k-1, jj]) { jj in range of [0, ii-1] }
// = max(f[k, ii-1], prices[ii] + max(f[k-1, jj] - prices[jj]))
// f[0, ii] = 0; 0 times transation makes 0 profit
// f[k, 0] = 0; if there is only one price data point you can't make any money no matter how many times you can trade
if (prices.size() <= 1) return 0;
else {
int K = 2; // number of max transation allowed
int maxProf = 0;
vector<vector<int>> f(K+1, vector<int>(prices.size(), 0));
for (int kk = 1; kk <= K; kk++) {
int tmpMax = f[kk-1][0] - prices[0];
for (int ii = 1; ii < prices.size(); ii++) {
f[kk][ii] = max(f[kk][ii-1], prices[ii] + tmpMax);
tmpMax = max(tmpMax, f[kk-1][ii] - prices[ii]);
maxProf = max(f[kk][ii], maxProf);
}
}
return maxProf;
}
}
};
leetcode 很好的一点就是将一类题目放在一起,好下面我们开始解决问题:
贪心算法: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/#/description
public class Solution {
public int maxProfit(int[] prices) {
if(prices==null) return 0;
int len = prices.length;
if(len==1) return 0;
int i = 0;
int j = 1;
int res = 0;
while(j<=len-1){
if(prices[j]>prices[i])
{
res += prices[j]-prices[i];
}
i = j;
j = j +1;
}
return res;
}
}