Skip to content

力扣链接:122.买卖股票的最佳时机 II

难度:⭐⭐

✏️ 方法一:

解题关键词:动态规划

解题思路:用一个二维数组 dp,然后 dp[0][0] 代表第一天持有现金,dp[0][1]代表第一天持有股票,不断往后遍历,然后更新 dp 数组,最大利润肯定是最后一天持有现金的时候。

typescript
function maxProfit(prices: number[]): number {
  // 二维数组 dp[0][0]代表持有现金 dp[0][1]代表持有股票
  const dp: number[][] = [[0, -prices[0]]];

  for (let i = 1; i < prices.length; i++) {
    // 第 i 天:持有现金,就是昨天持有现金 和 昨天持有股票今天卖掉,取一个最大值
    const cash = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
    // 第 i 天:持有股票,就是昨天持有股票 和 昨天持有现金今天买入,取一个最大值
    const hold = Math.max(dp[i - 1][0] - prices[i], dp[i - 1][1]);

    dp[i] = [cash, hold];
  }

  // 最后一天持有现金时,利润最大化
  return dp[dp.length - 1][0];
}

✏️ 方法二:

解题关键词:贪心

解题思路:只要第二天的股票价格比第一天价格高,我们就交易。贪心

typescript
function maxProfit(prices: number[]): number {
  let result = 0;

  for (let i = 1; i < prices.length; i++) {
    // 当天比前一天价格高,就交易,赚差价
    if (prices[i] > prices[i - 1]) {
      result += prices[i] - prices[i - 1];
    }
  }

  return result;
}