【LeetCode】122. 买卖股票的最佳时机 II

122. 买卖股票的最佳时机 II

题目

给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。

在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。然而,你可以在 同一天 多次买卖该股票,但要确保你持有的股票不超过一股。

返回 你能获得的 最大 利润 。

例子

输入:prices = [7,1,5,3,6,4]

输出:7

解释:在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3。
最大总利润为 4 + 3 = 7

解法一

  1. 若价格一直往下跌,不买入
  2. 假设第一天买入,若买入后价格往下跌,应该下一天买入
  3. 若下一天价格往下跌,应该当天卖出
  4. 若到最后一天,应该清盘,若之前买入卖出,否则维持现状
public int maxProfit(int[] prices) {
    if (prices == null || prices.length <= 1)
        return 0;

    int maxProfit = 0, minPrice = prices[0];
    for (int i = 1; i < prices.length; i++) {
        if (prices[i] < minPrice) {          // 若价格比之前低,应该买入
            minPrice = prices[i];
        } else if (i == prices.length - 1) { // 最后一天,强制清盘
            if (prices[i] - minPrice > 0) {
                maxProfit += (prices[i] - minPrice);
            }
        } else if (prices[i + 1] < prices[i]) { // 若后一天价格比当前低&&之前已经买入,就应该当天卖出
            maxProfit += (prices[i] - minPrice);
            minPrice = prices[i + 1];
        }

        System.out.println(
                String.join(",", String.valueOf(prices[i]), String.valueOf(minPrice), String.valueOf(maxProfit)));
    }
    return maxProfit;
}

解法二

贪心算法,若当天价格比前一天高,即可卖出,获取利润,统计结果利润

public int maxProfit(int[] prices) {
    if (prices == null || prices.length <= 1)
        return 0;

    int maxProfit = 0;
    for (int i = 1; i < prices.length; i++) {
        maxProfit += Math.max(0, prices[i] - prices[i - 1]);
    }
    return maxProfit;
}
posted @ 2025-09-25 18:29  WilsonPan  阅读(16)  评论(0)    收藏  举报