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]
Credits:
public class Solution {
public int maxProfit(int[] prices) {
//buy[i]=max(buy[i-1],sell[i-2]-prices[i])在当前节点买入和之前所有可能买入节点的最大值
//sell[i]=max(sell[i-1],buy[i-1]+prices[i])在当前结点卖出和此节点以前所有节点卖出的最大值
//当前的buy和sell的最大值依赖前一个和前2个
int n=prices.length;
//初始值,在刚刚开始时,之前的卖出得到的利润为0;之前的买入最大利润为负数的最大值。因为刚刚开始不可能是卖。
int pre_buy,buy=Integer.MIN_VALUE,pre_sell=0,sell=0;
//pre表示前一天买入和卖出,buy和sell表示当天买入和卖出
for(int i=0;i<n;i++){
pre_buy=buy;
buy=Math.max(pre_buy,pre_sell-prices[i]);
pre_sell=sell;
sell=Math.max(sell,pre_buy+prices[i]);
}
return sell;
}
}
本文介绍了一种用于计算股票交易最大利润的算法。该算法允许多次买卖操作,并考虑了冷却期限制,即卖出后不能立即购买。通过动态规划方法,跟踪买入和卖出的最佳时机,实现了利益最大化。
676

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



