[leetcode hot 150]第一百二十二题,买卖股票的最佳时机Ⅱ

题目:

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

在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。

返回 你能获得的 最大 利润

  1. 初始化:
    • 如果数组长度小于等于1,直接返回0(无法获利)
    • hold = -prices:第一天买入股票,利润为负
    • notHold = 0:第一天不买股票,利润为0
  2. 遍历每一天(从第二天开始):
    • 更新 hold[i]
      hold[i] = Math.max(hold[i - 1], notHold[i - 1] - prices[i])
      意味着今天持有股票的最大利润可能来自:
      • 昨天就持有股票(hold[i - 1]
      • 昨天不持有,今天买入(notHold[i - 1] - prices[i]
    • 更新 notHold[i]
      notHold[i] = Math.max(notHold[i - 1], hold[i - 1] + prices[i])
      意味着今天不持有股票的最大利润可能来自:
      • 昨天就不持有股票(notHold[i - 1]
      • 昨天持有,今天卖出(hold[i - 1] + prices[i]
java 复制代码
public class no_122 {
    public static void main(String[] args) {
        int[] price = {1, 2, 3, 4, 5};
        System.out.println(maxProfit(price));
    }

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

        int[] hold = new int[n];
        int[] notHold = new int[n];

        hold[0] = -prices[0];
        notHold[0] = 0;

        for (int i = 1; i < n; i++) {
            //  今天持有股票的最大利润 = max(昨天持有,昨天不持有今天买入)
            hold[i] = Math.max(hold[i - 1], notHold[i - 1] - prices[i]);

            //  今天不持有股票的最大利润 = max(昨天就不持有, 昨天持有今天卖出)
            notHold[i] = Math.max(notHold[i - 1], hold[i - 1] + prices[i]);

        }
        return notHold[n - 1];

    }
}
相关推荐
远瞻。21 分钟前
【论文阅读】人脸修复(face restoration ) 不同先验代表算法整理2
论文阅读·算法
先做个垃圾出来………3 小时前
哈夫曼树(Huffman Tree)
数据结构·算法
phoenix@Capricornus5 小时前
反向传播算法——矩阵形式递推公式——ReLU传递函数
算法·机器学习·矩阵
Inverse1625 小时前
C语言_动态内存管理
c语言·数据结构·算法
数据与人工智能律师5 小时前
虚拟主播肖像权保护,数字时代的法律博弈
大数据·网络·人工智能·算法·区块链
wuqingshun3141596 小时前
蓝桥杯 16. 外卖店优先级
c++·算法·职场和发展·蓝桥杯·深度优先
YouQian7726 小时前
2025春训第十九场
算法
CodeJourney.6 小时前
基于MATLAB的生物量数据拟合模型研究
人工智能·爬虫·算法·matlab·信息可视化
Epiphany.5567 小时前
素数筛(欧拉筛算法)
c++·算法·图论
爱吃涮毛肚的肥肥(暂时吃不了版)7 小时前
项目班——0510——JSON网络封装
c++·算法·json