57 lines
2.2 KiB
Java
57 lines
2.2 KiB
Java
package dynamic_programming;
|
||
/**
|
||
* 题目: 121. 买卖股票的最佳时机 (maxProfit)
|
||
* 描述:给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
|
||
* 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
|
||
* 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
|
||
|
||
* 示例 1:
|
||
输入:[7,1,5,3,6,4]
|
||
输出:5
|
||
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
|
||
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
|
||
|
||
* 链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/
|
||
*/
|
||
//需要琢磨
|
||
//二刷会做
|
||
public class MaxProfit {
|
||
public int maxProfit(int[] prices) {
|
||
int n = prices.length;
|
||
if (n < 2) return 0;
|
||
|
||
// dp[i][0]:第 i 天持有股票的最大收益
|
||
// dp[i][1]:第 i 天不持有股票的最大收益
|
||
int[][] dp = new int[n][2];
|
||
|
||
// 边界:第 0 天
|
||
dp[0][0] = -prices[0];
|
||
dp[0][1] = 0;
|
||
|
||
for (int i = 1; i < n; i++) {
|
||
// 今天持有:要么延续昨天持有,要么今天买入(只能买一次)
|
||
dp[i][0] = Math.max(dp[i - 1][0], -prices[i]);
|
||
// 今天不持有:要么延续昨天不持有,要么今天卖出
|
||
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
|
||
}
|
||
|
||
// 最终答案:最后一天不持有时的最大收益
|
||
return dp[n - 1][1];
|
||
}
|
||
public int maxProfit1(int[] prices) {
|
||
int n = prices.length;
|
||
if (n < 2) return 0;
|
||
|
||
int hold = -prices[0]; // 对应 dp[0][0]
|
||
int notHold = 0; // 对应 dp[0][1]
|
||
|
||
for (int i = 1; i < n; i++) {
|
||
// 注意更新顺序:先算不持有,再算持有也可以,但要保证用到的是前一天的状态
|
||
hold = Math.max(hold, -prices[i]);
|
||
notHold = Math.max(notHold, hold + prices[i]);
|
||
}
|
||
|
||
return notHold;
|
||
}
|
||
}
|