121. 买卖股票的最佳时机
题目描述
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
示例
输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
解题思路
class Solution {
public int maxProfit(int[] prices) {
int ans = 0, n = prices.length;
int buyPrice = prices[0];
for (int price : prices) {
if (price < buyPrice) {
// 当前买到的最低价
buyPrice = price;
} else {
// 比较差值, 当前卖出的利润
int profit = price - buyPrice;
ans = Math.max(profit, ans);
}
}
return ans;
}
}
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
//dp[0]: 手上没有股票的最大价值 dp[1]: 手上持有股票的最大价值
int[] dp = new int[2];
dp[0] = 0;
dp[1] = -prices[0];
for (int i = 1; i < len; i++) {
//第i天没有股票, 可以是前一天也没有, 也可以是今天卖了之前的股票
dp[0] = Math.max(dp[0], dp[1] + prices[i]);
//第i天有股票, 可以是前一天就有, 也可以是今天买的股票
dp[1] = Math.max(dp[1], -prices[i]);
}
//最后一天手上一定是没有股票的,有的话就受益一定没有最后一天全抛出的多,所以是dp[0]
return dp[0];
}
}
122. 买卖股票的最佳时机 II
题目描述
给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。然而,你可以在 同一天 多次买卖该股票,但要确保你持有的股票不超过一股。
返回 你能获得的 最大 利润 。
示例
输入: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 。
解题思路
class Solution {
public int maxProfit(int[] prices) {
int ans = 0, n = prices.length;
for (int i = 0; i < n; i++) {
if (i > 0 && prices[i] > prices[i - 1]) {
ans += prices[i] - prices[i - 1];
}
}
return ans;
}
}
123. 买卖股票的最佳时机 III
题目描述
给定一个数组,它的第 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 。
解题思路
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length, ans = 0;
/*
dp[0]: 第i天无操作
dp[1]: 第i天第一次持有改股的最大价值
dp[2]: 第一次不持有
dp[3]: 第二次持有
dp[4]: 第二次不持有
*/
int[] dp = new int[5];
dp[1] = -prices[0];
dp[3] = -prices[0];
for (int i = 1; i < n; i++) {
dp[1] = Math.max(dp[1], -prices[i]);
dp[2] = Math.max(dp[1] + prices[i], dp[2]);
dp[3] = Math.max(dp[2] - prices[i], dp[3]);
dp[4] = Math.max(dp[3] + prices[i], dp[4]);
}
return dp[4];
}
}
评论