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

    }
}
相关推荐
NAGNIP6 小时前
万字长文!回归模型最全讲解!
算法·面试
知乎的哥廷根数学学派6 小时前
面向可信机械故障诊断的自适应置信度惩罚深度校准算法(Pytorch)
人工智能·pytorch·python·深度学习·算法·机器学习·矩阵
666HZ6668 小时前
数据结构2.0 线性表
c语言·数据结构·算法
余瑜鱼鱼鱼8 小时前
Java数据结构:从入门到精通(十二)
数据结构
实心儿儿8 小时前
Linux —— 基础开发工具5
linux·运维·算法
charlie1145141919 小时前
嵌入式的现代C++教程——constexpr与设计技巧
开发语言·c++·笔记·单片机·学习·算法·嵌入式
清木铎10 小时前
leetcode_day4_筑基期_《绝境求生》
算法
清木铎10 小时前
leetcode_day10_筑基期_《绝境求生》
算法
j_jiajia11 小时前
(一)人工智能算法之监督学习——KNN
人工智能·学习·算法
源代码•宸11 小时前
Golang语法进阶(协程池、反射)
开发语言·经验分享·后端·算法·golang·反射·协程池