题目
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
- 来源:力扣(LeetCode)
- 链接:leetcode-cn.com/problems/be…
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一
思路
每次都找一下后面比当前值大的数据。两层循环解决。在LeetCode上会超时。
代码
public int maxProfit(int[] prices) {
int res = 0;
for (int i = 0; i < prices.length; i++) {
for (int j = i + 1; j < prices.length; j++) {
res = Math.max(res, prices[j] - prices[i]);
}
}
return res;
}
复杂度
时间复杂度:O(n^2) 空间复杂度:O(1)
解法二
思路
其实每次都是在找当前值之后的最大值。那么完全可以在一次遍历中找到这个最大值。 dp[i]表示i之后(包含自己)的最大值。 这样从后往前找就可以了。
代码
public int maxProfit(int[] prices) {
if (prices.length == 0) {
return 0;
}
int[] dp = new int[prices.length];
dp[prices.length - 1] = prices[prices.length - 1];
for (int i = prices.length - 2; i >= 0; i--) {
dp[i] = Math.max(prices[i], dp[i+1]);
}
int res = 0;
for (int i = 0; i < prices.length; i++) {
res = Math.max(res, dp[i] - prices[i]);
}
return res;
}
复杂度
时间复杂度:O(n) 空间复杂度:O(n)
解法三
思路
能不能将上面的空间复杂度降低呢? 其实没有必要将所有的最大值都记录下来。
代码
public int maxProfit(int[] prices) {
int maxProfit = 0;
int maxPrice = 0;
for (int i = prices.length - 1; i >= 0; i--) {
maxPrice = Math.max(maxPrice, prices[i]);
maxProfit = Math.max(maxProfit, maxPrice - prices[i]);
}
return maxProfit;
}
复杂度
时间复杂度:O(n) 空间复杂度:O(1)
解法四
思路
每一天都有2个状态,要么买,要么卖,要么什么都不操作。 第i天的最大收益可以这么转化。
- buy1(i) = Math.max(不买入 buy1(i-1), -price[i])
- sell1(i) = Math.max(不卖 sell1(i-1), buy1(i) + price[i])
代码
public int maxProfit(int[] prices) {
int buy1 = -prices[0];
int sell1 = 0;
for (int i = 1; i < prices.length; i++) {
buy1 = Math.max(buy1, -prices[i]);
sell1 = Math.max(sell1, buy1 + prices[i]);
}
return sell1;
}
复杂度
- 时间复杂度:O(n)
- 空间复杂度:O(1)
解法五
代码
class Solution {
public int maxProfit(int[] prices) {
//dp[i][0] 第i天没有股票的最大收益
//dp[i][1] 第i天有股票的最大收益
int n = prices.length;
int[][] dp = new int[n][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < n; i++) {
// 没有股票,要么前一天也没有股票,要么卖出今天的股票,一旦卖出肯定会有收益
dp[i][0] = Math.max(dp[i-1][0], prices[i] + dp[i-1][1]);
dp[i][1] = Math.max(dp[i-1][1], -prices[i]);
}
return dp[n-1][0];
}
}