123. Best Time to Buy and Sell Stock III
You are given an array prices where prices[i] is the price of a given stock on the ith day.
Find the maximum profit you can achieve. You may complete at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
题目解析:
- 最多两次交易,所以可以分为五种状态:初始状态,第一次持有,第一次卖出,第二次持有,第二次卖出
- 定义二维数组:第一维是天数,第二维是状态
- 当前天的状态只与前一天的状态有关,而且当前状态只与前一个状态有关,所以可以使用一维数组
代码:
// 二维数组
class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 1) return 0;
// 五种状态:初始状态,第一次持有,第一次卖出,第二次持有,第二次卖出
int[][] dp = new int[prices.length][5];
dp[0][1] = -prices[0];
dp[0][3] = -prices[0];
for (int i = 1; i < prices.length; i++) {
dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]);
dp[i][2] = Math.max(dp[i-1][2], dp[i-1][1] + prices[i]);
dp[i][3] = Math.max(dp[i-1][3], dp[i-1][2] - prices[i]);
dp[i][4] = Math.max(dp[i-1][4], dp[i-1][3] + prices[i]);
}
return dp[prices.length-1][4];
}
}
// 一维数组
class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 1) return 0;
// 五种状态:初始状态,第一次持有,第一次卖出,第二次持有,第二次卖出
int[] dp = new int[5];
dp[1] = -prices[0];
dp[3] = -prices[0];
for (int i = 1; i < prices.length; i++) {
dp[1] = Math.max(dp[1], dp[0] - prices[i]);
dp[2] = Math.max(dp[2], dp[1] + prices[i]);
dp[3] = Math.max(dp[3], dp[2] - prices[i]);
dp[4] = Math.max(dp[4], dp[3] + prices[i]);
}
return dp[4];
}
}
188. Best Time to Buy and Sell Stock IV
You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.
Find the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
题目解析:
- 与上一题类似
代码:
class Solution {
public int maxProfit(int k, int[] prices) {
if (prices.length == 1) return 0;
int[] dp = new int[k * 2 + 1];
for (int i = 0; i < k * 2 + 1; i++) {
if (i % 2 == 1) dp[i] = -prices[0];
}
for (int i = 1; i < prices.length; i++) {
for (int j = 1; j < k * 2 + 1; j++) {
if (j % 2 == 0) {
dp[j] = Math.max(dp[j], dp[j - 1] + prices[i]);
} else {
dp[j] = Math.max(dp[j], dp[j - 1] - prices[i]);
}
}
}
return dp[k * 2];
}
}