题目
给你一个整数数组 prices
,其中 prices[i]
表示某支股票第 i
天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
示例 1:
输入: prices = [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3。
最大总利润为 4 + 3 = 7 。
题解
方式一:双指针
复杂度:O(n)
public int maxProfit(int[] prices) {
// 一天无法交易获利
if (prices.length == 1) {
return 0;
}
int low = prices[0]; // low指针记录最低点
int ans = 0;
// 找到每一个上坡,i代表high指针
for (int i = 0; i < prices.length - 1; i++) {
if (prices[i + 1] < prices[i]) {
// prices[i]是当前上坡最高点
ans = ans + prices[i] - low;
// 交易完更新low到下一位
low = prices[i + 1];
} else if (i == prices.length - 2) {
// 整个数组都是长坡的情况
ans = ans + prices[i + 1] - low;
}
}
return ans;
}
这种方式在连续下坡的时候多了很多无效的计算,prices[i] - low = 0,只是为了更新low
方式二:贪心
复杂度:O(n)
public int maxProfit(int[] prices) {
if (prices.length == 1) {
return 0;
}
int ans = 0;
// 不找完整的上坡,而是拆分成每一个长度为1的长坡
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
ans += prices[i] - prices[i - 1];
}
}
return ans;
}
方式三:动态规划
复杂度:O(n)
// 不好想,慢慢习惯这种思维
public int maxProfit(int[] prices) {
if (prices.length == 1) {
return 0;
}
int[][] dp = new int[prices.length][2];
dp[0][0] = 0; // 第0天没有持有股票的最大利润
dp[0][1] = -prices[0]; // 第0天持有股票的最大利润
for (int i = 1; i < prices.length; i++) {
// 第i天没有股票有两种情况,i - 1天就没有股票,i - 1天有但是i天卖了
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
// 第i天有股票有两种情况,i - 1天就有股票,i - 1天没有但是i天买了
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
// 最后一天不持有股票的最大利润
return dp[prices.length - 1][0];
}
总结
算法:双指针
、动态规划
、贪心