121. 买卖股票的最佳时机
视频讲解:动态规划之 LeetCode:121.买卖股票的最佳时机1_哔哩哔哩_bilibili
class Solution {
public int maxProfit(int[] prices) {
int minPurchasePrice = Integer.MAX_VALUE;
int result = 0;
for(int j = 0; j < prices.length; j++){
minPurchasePrice = Math.min(prices[j], minPurchasePrice);
result = Math.max(prices[j] - minPurchasePrice, result);
}
return result;
}
}
122.买卖股票的最佳时机II
视频讲解:动态规划,股票问题第二弹 | LeetCode:122.买卖股票的最佳时机II_哔哩哔哩_bilibili
class Solution {
public int maxProfit(int[] prices) {
int length = prices.length;
int[][] profitMatrix = new int[length][2];
profitMatrix[0][0] = 0;
profitMatrix[0][1] = -prices[0];
for (int day = 1; day < length; ++day) {
profitMatrix[day][0] = Math.max(profitMatrix[day - 1][0], profitMatrix[day - 1][1] + prices[day]);
profitMatrix[day][1] = Math.max(profitMatrix[day - 1][1], profitMatrix[day - 1][0] - prices[day]);
}
return profitMatrix[length - 1][0];
}
}
123.买卖股票的最佳时机III
这道题一下子就难度上来了,关键在于至多买卖两次,这意味着可以买卖一次,可以买卖两次,也可以不买卖。
视频讲解:动态规划,股票至多买卖两次,怎么求? | LeetCode:123.买卖股票最佳时机III_哔哩哔哩_bilibili
class Solution {
public int maxProfit(int[] prices) {
int length = prices.length;
if (prices.length == 0) return 0;
int[][] profitMatrix = new int[length][5];
profitMatrix[0][1] = -prices[0];
profitMatrix[0][3] = -prices[0];
for (int i = 1; i < length; i++) {
profitMatrix[i][1] = Math.max(profitMatrix[i - 1][1], -prices[i]);
profitMatrix[i][2] = Math.max(profitMatrix[i - 1][2], profitMatrix[i - 1][1] + prices[i]);
profitMatrix[i][3] = Math.max(profitMatrix[i - 1][3], profitMatrix[i - 1][2] - prices[i]);
profitMatrix[i][4] = Math.max(profitMatrix[i - 1][4], profitMatrix[i - 1][3] + prices[i]);
}
return profitMatrix[length - 1][4];
}
}