知序
返回
保存草稿
发布
H1
H2
H3
1
2
3
Excalidraw 图
AI 写作
AI 优化
目录
输入内容后显示目录
Markdown
# 18 - 买卖股票的最佳时机 ## 题目(LeetCode 121) 给定股票每天的价格,只能买卖一次,求最大利润。 ## 解法:一次遍历 ```java class Solution { public int maxProfit(int[] prices) { int minPrice = Integer.MAX_VALUE, maxProfit = 0; for (int price : prices) { minPrice = Math.min(minPrice, price); maxProfit = Math.max(maxProfit, price - minPrice); } return maxProfit; } } ``` ## 复杂度 - 时间 O(n),空间 O(1) ## 一句话总结 维护历史最低价,每天算当天卖出的利润,取最大值。 ## 解法二:动态规划 定义 `dp[i][0]` 为第 i 天不持股的最大利润,`dp[i][1]` 为持股的最大利润。 ```java class Solution { public int maxProfit(int[] prices) { int n = prices.length; // dp[i][0]: 第i天不持股, dp[i][1]: 持股 int hold = -prices[0], notHold = 0; for (int i = 1; i < n; i++) { notHold = Math.max(notHold, hold + prices[i]); hold = Math.max(hold, -prices[i]); // 只能买一次,所以是 -prices[i] } return notHold; } } ``` ## 解法对比 | | 解法一(一次遍历) | 解法二(动态规划) | |--|--------|--------| | 时间复杂度 | O(n) | O(n) | | 空间复杂度 | O(1) | O(1) | | 特点 | 直观,推荐 | 状态机框架,易扩展到买卖多次等变体 |
预览
发布文章
添加摘要让读者更快了解文章内容
取消
确认发布
AI 写作助手
输入一个主题,AI 将为你生成一篇 Markdown 博客文章
AI 正在写作中...
取消
开始生成
AI 优化助手
描述你的修改需求,AI 将在原文基础上进行补充或微调
AI 正在优化中...
取消
开始优化
画布
从已有图里选
✕
图名
保存后生成 /images/excalidraw/<图名>.svg(只能用字母、数字、短横线、下划线、点)
取消
保存并插入