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

    }
}
相关推荐
筵陌几秒前
算法:模拟
算法
Queenie_Charlie28 分钟前
小陶与杠铃片
数据结构·c++·树状数组
We་ct31 分钟前
LeetCode 205. 同构字符串:解题思路+代码优化全解析
前端·算法·leetcode·typescript
renhongxia144 分钟前
AI算法实战:逻辑回归在风控场景中的应用
人工智能·深度学习·算法·机器学习·信息可视化·语言模型·逻辑回归
CoderCodingNo1 小时前
【GESP】C++四级/五级练习题 luogu-P1223 排队接水
开发语言·c++·算法
民乐团扒谱机1 小时前
【AI笔记】精密光时频传递技术核心内容总结
人工智能·算法·光学频率梳
云深处@1 小时前
【C++】AVL树
数据结构
CoderCodingNo1 小时前
【GESP】C++五级/四级练习题 luogu-P1413 坚果保龄球
开发语言·c++·算法
Yvonne爱编码1 小时前
JAVA数据结构 DAY4-ArrayList
java·开发语言·数据结构
2301_822366352 小时前
C++中的命令模式变体
开发语言·c++·算法