// 买卖股票的最佳时机
// 给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
// 设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
// 输入:prices = [3,3,5,0,0,3,1,4]
// 输出:6
// 解释:在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。
// 随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。
public static int maxProfit(int[] prices){
int n=prices.length;
int buy1=-prices[0],sell1=0;
int buy2=-prices[0],sell2=0;
for (int i = 1; i <n ; i++) {
buy1=Math.max(buy1,-prices[i]);
sell1=Math.max(sell1,buy1+prices[i]);
buy2=Math.max(buy2,sell1-prices[i]);
sell2=Math.max(sell2,buy2+prices[i]);
}
return sell2;
}
买卖股票的最佳时机
最新推荐文章于 2025-12-27 16:49:17 发布
本文介绍了一种算法,用于计算在给定股票价格数组中通过最多两次交易获取的最大利润。通过动态规划的方法,找出每个时间点的买入和卖出最优策略。例如,对于prices=[3,3,5,0,0,3,1,4],算法返回6,展示了如何在特定价格波动中实现最大收益。

827

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



