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

    }
}
相关推荐
源代码•宸3 小时前
Leetcode—620. 有趣的电影&&Q3. 有趣的电影【简单】
数据库·后端·mysql·算法·leetcode·职场和发展
2301_800256113 小时前
地理空间数据库中的CPU 和 I/O 开销
数据库·算法·oracle
一个不知名程序员www4 小时前
算法学习入门---结构体和类(C++)
c++·算法
XFF不秃头6 小时前
力扣刷题笔记-旋转图像
c++·笔记·算法·leetcode
王老师青少年编程6 小时前
csp信奥赛C++标准模板库STL案例应用3
c++·算法·stl·csp·信奥赛·lower_bound·标准模版库
有为少年7 小时前
Welford 算法 | 优雅地计算海量数据的均值与方差
人工智能·深度学习·神经网络·学习·算法·机器学习·均值算法
Ven%7 小时前
从单轮问答到连贯对话:RAG多轮对话技术详解
人工智能·python·深度学习·神经网络·算法
山楂树の7 小时前
爬楼梯(动态规划)
算法·动态规划
谈笑也风生7 小时前
经典算法题型之复数乘法(二)
开发语言·python·算法