// 定义dp数组,表示到前i天最大利润, dp[i] = Math.max(dp[i - 1](昨天卖的), prices[i] - minPrice (今天卖的))
class Solution {
public int maxProfit(int[] prices) {
// 1. dp数组表示 前i天最大利润
int length = prices.length;
int[] dp = new int[length];
dp[0] = 0; // 第一天的利润为0
int minPrice = prices[0]; // 前i天买入的最低价格
// 2. dp递推:前i天的最大利润 = max(前i-1天的最大利润, 今天卖出的价格-前i-1天的最低价格)
for (int i = 1; i < length; i++) {
dp[i] = Math.max(dp[i - 1], prices[i] - minPrice);
minPrice = Math.min(minPrice, prices[i]);
}
return dp[length - 1];
}
}
Hot100【十四】:121.买卖股票的最佳时机_
于 2024-04-08 23:20:23 首次发布