【题目描述】
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
- You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
- After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2] maxProfit = 3 transactions = [buy, sell, cooldown, buy, sell]【解题思路】
参考https://discuss.leetcode.com/topic/30421/share-my-thinking-process
【代码】
class Solution {
public:
int maxProfit(vector<int>& prices) {
int buy=INT_MIN,sell=0,prev_sell=0,prev_buy=0;
for(int i=0;i<prices.size();i++){
prev_buy=buy;
buy=max(prev_sell-prices[i],prev_buy);
prev_sell=sell;
sell=max(prev_buy+prices[i],prev_sell);
}
return sell;
}
};
本文介绍了一种算法,用于解决股票交易中如何最大化利润的问题。该算法考虑了限制条件,如不能同时进行多笔交易及卖出后一天内不可再买进等。通过动态规划的方法实现了最优解。
681

被折叠的 条评论
为什么被折叠?



