LeetCode 123 Best Time to Buy and Sell Stock III
来源:互联网 发布:淘宝查询买家退货率 编辑:程序博客网 时间:2024/05/22 12:56
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).
front[i] 表示区间[0,i]的最大利润,back[i] 表示区间[i,n-1]的最大利润,n表示总天数。最大利润就是 max{ front[i]+back[i] } 0<=i<=n-1.
public int maxProfit3(int[] prices) {if (prices.length == 0) return 0;int minbuy = prices[0], profit = 0;int[] front = new int[prices.length];front[0] = 0;int[] back = new int[prices.length];back[prices.length - 1] = 0;for (int i = 1; i < prices.length; i++) {minbuy = Math.min(prices[i], minbuy);front[i] = Math.max(front[i - 1], prices[i] - minbuy);}for (int i = prices.length - 2, maxSell = prices[prices.length - 1]; i > 0; i--) {maxSell = Math.max(prices[i], maxSell);back[i] = Math.max(back[i - 1], maxSell - prices[i]);}for (int i = 0; i <prices.length ; i++) {profit = Math.max(front[i]+back[i],profit);}return profit;}
二刷
public int maxProfit3(int[] prices) {if (prices.length<2) return 0;int[] left=new int[prices.length];int res = 0, profit = 0;for (int i = 1; i <prices.length ; i++) {profit += prices[i] - prices[i - 1];if (profit < 0) profit = 0;res = Math.max(profit, res);left[i] = res;}int right = 0,max = res;profit = 0;for (int i = prices.length-2; i >0 ; i--) {profit += prices[i+1] - prices[i ];if (profit < 0) profit = 0;right = Math.max(profit, right);max = Math.max(max ,right+left[i]);}return max;}
0 0
- LeetCode 123: Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III [123]
- LeetCode 123 Best Time to Buy and Sell Stock III
- [leetcode 123] Best Time to Buy and Sell Stock III
- leetcode || 123、Best Time to Buy and Sell Stock III
- leetcode-123 Best Time to Buy and Sell Stock III
- leetcode 123: Best Time to Buy and Sell Stock III
- 123 Best Time to Buy and Sell Stock III [Leetcode]
- Best Time to Buy and Sell Stock III - LeetCode 123
- LeetCode 123: Best Time to Buy and Sell Stock III
- LeetCode 123 Best Time to Buy and Sell Stock III
- LeetCode 123 -- Best Time to Buy and Sell Stock III
- Leetcode 123 Best Time to Buy and Sell Stock III
- LeetCode 123 Best Time to Buy and Sell Stock III
- Leetcode Best Time to Buy and Sell Stock III 123
- [Leetcode 123] Best Time to Buy and Sell Stock III
- **Leetcode 123 Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- linux 硬盘挂载 fdisk parted命令
- sqlserver2008新增只有查询查询权限的账号
- SQL Server日志文件过大的处理
- SQL Server2008数据库不用连接的删除
- MySQL数据库备份和恢复
- LeetCode 123 Best Time to Buy and Sell Stock III
- Linux网络基础知识
- Java国际化程序
- node模块机制
- 保留两位小数
- linux环境变量配置文件
- LeetCode 70. Climbing Stairs
- Apache虚拟主机配置
- Android练习项目——知乎日报