Day49
121.买卖股票的最佳时机
贪心
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int minn = prices[0];
int maxn = 0;
for (int i = 1; i < n; i++) {
maxn = Math.max(prices[i] - minn, maxn);
minn = Math.min(prices[i], minn);
}
return maxn;
}
}
动态规划
dp数组的含义
dp[i][0] 表示第i天持有股票所得现金。
dp[i][1] 表示第i天不持有股票所得最多现金。
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int dp[][] = new int[n][2];
dp[0][0] = -prices[0];
dp[0][1] = 0;
for (int i = 1; i < prices.length; i++) {
dp[i][0] = Math.max(dp[i - 1][0], -prices[i]);
dp[i][1] = Math.max(dp[i - 1][0] + prices[i], dp[i - 1][1]);
}
return Math.max(dp[n - 1][0], dp[n - 1][1]);
}
}
122.买卖股票的最佳时机Ⅱ
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int dp[][] = new int[n][2];
dp[0][0] = -prices[0];
dp[0][1] = 0;
for (int i = 1; i < n; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
dp[i][1] = Math.max(dp[i - 1][0] + prices[i], dp[i - 1][1]);
}
return Math.max(dp[n - 1][0], dp[n - 1][1]);
}
}