当前位置: 首页 > news >正文

Day41--动态规划--121. 买卖股票的最佳时机,122. 买卖股票的最佳时机 II,123. 买卖股票的最佳时机 III

Day41–动态规划–121. 买卖股票的最佳时机,122. 买卖股票的最佳时机 II,123. 买卖股票的最佳时机 III

121. 买卖股票的最佳时机

方法:暴力

思路:

两层遍历

class Solution {public int maxProfit(int[] prices) {int n = prices.length;int res = Integer.MIN_VALUE;for (int i = 0; i < n; i++) {for (int j = i + 1; j < n; j++) {if (prices[j] > prices[i]) {res = Math.max(res, prices[j] - prices[i]);}}}return res == Integer.MIN_VALUE ? 0 : res;}
}

方法:贪心

思路:

记录取“最左”“最小”价格

class Solution {public int maxProfit(int[] prices) {int n = prices.length;int minPrice = Integer.MAX_VALUE;int res = 0;for (int i = 0; i < n; i++) {// 取“最左”“最小”价格minPrice = Math.min(minPrice, prices[i]);// 更新最大利润res = Math.max(res, prices[i] - minPrice);}return res;}
}

方法:动态规划

思路:

  1. dpi指的是在第i天,能获取的最大利润(手里的钱)
  2. 递推公式:
    1. 要么就是继续持有,要么买今天的(覆盖原来的)dp[0] = Math.max(dp[0], -prices[i]);
    2. 要么保持前些天卖出的钱,要么今天卖出dp[1] = Math.max(dp[1], dp[0] + prices[i]);
    3. 初始化:dp[0] = -prices[0]; dp[1] = 0;
    4. 遍历顺序:正序
// 动态规划
class Solution {public int maxProfit(int[] prices) {// dpi指的是在第i天,能获取的最大利润(手里的钱)// 每天交易,交易有买入卖出两种状态// dp[0]代表买入,dp[1]代表卖出int[] dp = new int[2];// 初始化dp[0] = -prices[0];dp[1] = 0;for (int i = 1; i < prices.length; i++) {// 解释一:要么就是继续持有,要么买今天的(覆盖原来的)// 解释二:这里就是取minPrice了,有没有看出来dp[0] = Math.max(dp[0], -prices[i]);// 解释一:要么保持前些天卖出的钱,要么今天卖出// 解释二:每天算一下,是今天卖出能赚取更多,还是按前些天卖的能赚更多dp[1] = Math.max(dp[1], dp[0] + prices[i]);}// 最后一天,肯定要卖出才有最大收益,所以返回dp[1]return dp[1];}
}

方法:动态规划

思路:

二维数组版本,第一次写的时候可以写这个,遍历出来,看到每一层的变化。

// 动态规划
class Solution {public int maxProfit(int[] prices) {int n = prices.length;if (n == 0) {return 0;}int[][] dp = new int[n][2];dp[0][0] -= prices[0];dp[0][1] = 0;for (int i = 1; i < n; i++) {dp[i][0] = Math.max(dp[i - 1][0], -prices[i]);dp[i][1] = Math.max(dp[i - 1][1], prices[i] + dp[i - 1][0]);}return dp[n - 1][1];}
}

122. 买卖股票的最佳时机 II

思路:


123. 买卖股票的最佳时机 III

思路:


http://www.lryc.cn/news/616041.html

相关文章:

  • LeetCode 组合总数
  • AI质检数据准备利器:基于Qt/QML 5.14的图像批量裁剪工具开发实战
  • Python 2025:最新技术趋势与展望
  • Text2SQL 自助式数据报表开发(Chat BI)
  • 解决 .NET Core 6.0 + PostgreSQL 网站首次连接缓慢问题
  • 嵌入式软件分层架构的设计原理与实践验证(有限状态机理解及结构体封装理解)
  • spring-ai整合PGVector实现RAG
  • WinForm之TreeView控件
  • Baumer高防护相机如何通过YoloV8深度学习模型实现道路坑洼的检测识别(C#代码UI界面版)
  • [激光原理与应用-223]:机械 - 机加厂加工机械需要2D还是3D图?
  • jvm有哪些垃圾回收器,实际中如何选择?
  • 本地WSL部署接入 whisper + ollama qwen3:14b 总结字幕校对增强版
  • Code Exercising Day 10 of “Code Ideas Record“:StackQueue part02
  • 低版本 IntelliJ IDEA 使用高版本 JDK 语言特性的问题
  • IDEA 如何导入系统设置
  • 基于ECharts的智慧社区数据可视化
  • IDEA 快捷编辑指南
  • IntelliJ IDEA 2025.2 重磅发布
  • OneCode 3.0 可视化功能全面分析:从开发者到用户的全场景解析
  • [激光原理与应用-214]:设计 - 皮秒紫外激光器 - 电控设计,高精度、高可靠性与智能化的全链路方案
  • 【渲染流水线】[几何阶段]-[归一化NDC]以UnityURP为例
  • SpringMVC的知识点总结
  • JDBC的连接过程(超详细)
  • 【Python 工具人快餐 · 第 6 份】
  • Redis缓存穿透、缓存击穿、缓存雪崩
  • 社交与职场中的墨菲定律
  • 故障诊断 | VMD-CNN-LSTM西储大学轴承故障诊断附MATLAB代码
  • vscode uv 发布一个python包:编辑、调试与相对路径导包
  • K8s四层负载均衡-service
  • 《Qt————Tcp通讯》