LeetCode 123 Best Time to Buy and Sell Stock III
2016-04-12 00:54
489 查看
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.
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; }
相关文章推荐
- 关于webroot与web-inf
- MySQL数据库备份和恢复
- SQL Server2008数据库不用连接的删除
- CSS3实战之box-sizing
- 【珍藏】高性能IO模型浅析
- 【珍藏】高性能IO模型浅析
- SQL Server日志文件过大的处理
- Net分布式系统之三:Keepalived+LVS+Nginx负载均衡之高可用
- sqlserver2008新增只有查询查询权限的账号
- SQL中的order by子句
- Python - cannot import OpenCV module?
- 栈的一些小小应用
- SQLServer数据库备份(语句方式)
- SQLServer 2008自动备份数据库
- [温故而知新] 《深度探索c++对象模型》——运行期语意
- 三种定时器的使用
- 深入Linux内存管理
- mysql修改root密码
- C语言模拟php basename() 函数
- mysql用户权限相关