【leetcode刷题笔记】Best Time to Buy and Sell Stock III
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
题解:DP
从前往后扫描一遍数组,用LeftToRight[i]记录(0,i)得到的最大利润;
从后往前扫描一遍数组,用RightToLeft[i]记录(i,n-1)得到的最大利润;
最终的最大利润是max(LeftToRight[i]+RightToLeft[i])。
举个例子,如果prices = {1,2,3,2,5,7},对应的
LeftToRight = {0,1,2,2,4,6}
RightToLeft = {6,5,5,5,2,0}
最终的最大利润就是2+5=7。表示在0~2(或0~3)这个区间取得利润2,并且在2~5(或者3~5)这个区间取得利润5,最终得到利润7.
代码如下:
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 if(prices == null || prices.length == 0) 4 return 0; 5 6 int[] LeftToRight = new int[prices.length]; 7 int[] RightToLeft = new int[prices.length]; 8 9 int minimal = prices[0]; 10 LeftToRight[0] = 0; 11 for(int i = 1;i < prices.length;i++){ 12 minimal = Math.min(minimal, prices[i]); 13 LeftToRight[i] = Math.max(LeftToRight[i-1], prices[i]-minimal); 14 } 15 16 int profit = 0; 17 //From Right to left 18 RightToLeft[prices.length-1] = 0; 19 int maximal = prices[prices.length-1]; 20 for(int i = prices.length-2;i >= 0;i--){ 21 maximal = Math.max(prices[i], maximal); 22 RightToLeft[i]= Math.max(RightToLeft[i+1], maximal-prices[i]); 23 profit = Math.max(profit, LeftToRight[i] + RightToLeft[i] ); 24 } 25 26 return Math.max(profit, LeftToRight[0]+RightToLeft[0]); 27 } 28 }
分类:
leetcode刷题总结
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了