买股票题目一种很好的通用解法
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/?tab=Description
题目是最多两次,但是下面的解法非常好,也能够覆盖仅仅一次的情况。
https://discuss.leetcode.com/topic/5934/is-it-best-solution-with-o-n-o-1/2
代码很简短,思路也非常好:
public class Solution { public int maxProfit(int[] prices) { int hold1 = Integer.MIN_VALUE, hold2 = Integer.MIN_VALUE; int release1 = 0, release2 = 0; for(int i:prices){ // Assume we only have 0 money at first release2 = Math.max(release2, hold2+i); // The maximum if we've just sold 2nd stock so far. hold2 = Math.max(hold2, release1-i); // The maximum if we've just buy 2nd stock so far. release1 = Math.max(release1, hold1+i); // The maximum if we've just sold 1nd stock so far. hold1 = Math.max(hold1, -i); // The maximum if we've just buy 1st stock so far. } return release2; ///Since release1 is initiated as 0, so release2 will always higher than release1. } }
但是上面对于最多N次这种更加通用的形式,就不太好用了。
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/?tab=Description
上面对于最多买n次类型的题目,要用到DP才行。
解法看这里:
https://discuss.leetcode.com/topic/8984/a-concise-dp-solution-in-java
其实含义也很明确:
tmpMax是当前时间状态持股之后的最大收益(很可能是负的)
t[i][j]是记录的实际收益。
public int maxProfit(int k, int[] prices) { int len = prices.length; if (k >= len / 2) return quickSolve(prices); int[][] t = new int[k + 1][len]; for (int i = 1; i <= k; i++) { int tmpMax = -prices[0]; for (int j = 1; j < len; j++) { t[i][j] = Math.max(t[i][j - 1], prices[j] + tmpMax); tmpMax = Math.max(tmpMax, t[i - 1][j - 1] - prices[j]); } } return t[k][len - 1]; } private int quickSolve(int[] prices) { int len = prices.length, profit = 0; for (int i = 1; i < len; i++) // as long as there is a price gap, we gain a profit. if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1]; return profit; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!