[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];

    }
}
相关推荐
罗西的思考10 小时前
【Agentic RL】Dressage Staleness 控制深度分析
人工智能·算法·机器学习
quaer10 小时前
弗洛伊德算法--判圈法寻找环的入口O(n) O(1)
数据结构·算法
文丑颜不良啊11 小时前
LeetCode51~75题目解析
leetcode
高晶11 小时前
无乘法器实现LC二阶滤波器:基于移位运算的快速算法与四种精度推导
算法·设计模式·程序员
ysbfsy11 小时前
大数计算思路
算法
高晶12 小时前
主从自动分配算法:平均值乘以设备数一半的选举基准值解析
算法·设计模式·程序员
学电子她就能回来吗12 小时前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode
用户老李12 小时前
反向传播计算梯度举例
算法
niyongsheng12 小时前
多智能体连续时间内路径规划:AA-SIPP(m) 的 Rust 实现与算法
算法·rust·机器人
302wanger13 小时前
DeepSeek-V4.1-Flash-1017 免费用到1024,速来
算法