123. 买卖股票的最佳时机 III(进阶版本【188. 买卖股票的最佳时机 IV】)
题目:
思路:
【1】利用了第一次与第二次结合同时买入和卖出的想法,获取这种操作下能赚取的最大值。
代码展示:
【1】123. 买卖股票的最佳时机 III
//时间1 ms 击败 100% //内存54.5 MB 击败 69.24% class Solution { public int maxProfit(int[] prices) { int n = prices.length; int buy1 = -prices[0], sell1 = 0; int buy2 = -prices[0], sell2 = 0; for (int i = 1; i < n; ++i) { buy1 = Math.max(buy1, -prices[i]); sell1 = Math.max(sell1, buy1 + prices[i]); buy2 = Math.max(buy2, sell1 - prices[i]); sell2 = Math.max(sell2, buy2 + prices[i]); } return sell2; } }
【2】188. 买卖股票的最佳时机 IV
//时间1 ms 击败 99.90% //内存39.3 MB 击败 90.2% class Solution { public int maxProfit(int k, int[] prices) { int n = prices.length; // 因为存在一买一卖,所以最大买卖次数便是数组的一半 k = Math.min(k, n / 2); if (k == 0) return 0; int[] buy = new int[k], sell = new int[k]; Arrays.fill(buy, -prices[0]); for (int i = 0; i < n; ++i) { buy[0] = Math.max(buy[0], -prices[i]); sell[0] = Math.max(sell[0], buy[0] + prices[i]); for (int j = 1 ; j < k; j++){ buy[j] = Math.max(buy[j], sell[j-1] - prices[i]); sell[j] = Math.max(sell[j], buy[j] + prices[i]); } } return sell[k-1]; } }
分类:
leetcode题目
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现