LeetCode-Best Time to Buy and Sell Stock III
来源:互联网 发布:天地图框架数据标准 编辑:程序博客网 时间:2024/05/21 06:44
题目描述
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).
思路分析
1、最开始我用的从后往前推的动态规划,失败告终。
2、百度之,转换思路,将0-n,划分为0 ~ i , (i+1) ~ n两段,这样就可以将问题转化为Best Time to Buy and Sell Stock问题。
3、这道题的关键在于是可以买卖两次,那么不妨这样想,第一次买卖是按照时间顺序的,即我们从第一天开始扫描,记录到今天为止的最低货物价格,然后判定若在今天卖出,是否能够获取更大的利润,记为数组left[day]。而第二次买卖是逆时间顺序的,即从最后一天开始扫描,记录到今天为止的最高货物价格,然后判定若在今天买入,是否能够获取更大的利润,记为数组right[day](因为我们已经知道以后的几天里面最高价格了,这就是Best Time to But and Sell Stock的逆向)。
4、做完以上工作之后,开始遍历left和right,找到left[day]和right[day]相加的最大值。
5、关于采用此种方法是否可能导致两次交易时间发生交叉(即第一买卖:第1天买入,第8天卖出。第二次买卖:第2天买入,第16天卖出)导致不能否符合题目的问题,在第4步已经解决了。left[day]表示到day天之前的最好的一次交易,right[day]表示day天之后的最好的一次交易。二者以day天为分界线,将两次交易隔开了。
代码如下:
public class Solution { public int maxProfit(int[] prices) { if(null == prices || 0 == prices.length) { return 0; } int[] left = new int[prices.length]; int[] right = new int[prices.length]; int min = prices[0]; for(int day = 1; day <= prices.length - 1; ++day) { //确定当前最大利润 left[day] = left[day - 1] > prices[day] - min ? left[day - 1] : prices[day] - min; min = prices[day] < min? prices[day] : min; } int max = prices[prices.length - 1]; for(int day = prices.length - 1; day >= 1; --day) { //确定当前最大利润 right[day] = right[day - 1] > max - prices[day] ? right[day - 1] : max - prices[day]; max = prices[day] > max? prices[day] : max; } int re = 0; for(int day = 0; day <= prices.length - 1; ++day) { re = left[day] + right[day] > re ? left[day] + right[day] : re; } return re; }}
- LeetCode Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock III
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- leetcode 62: Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- 【leetcode】Best Time to Buy and Sell Stock III
- LeetCode - Best Time to Buy and Sell Stock III
- LeetCode之Best Time to Buy and Sell Stock III
- [LeetCode]Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III
- [Leetcode]Best Time to Buy and Sell Stock III
- [leetcode]Best Time to Buy and Sell Stock III
- leetcode题目:Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- LeetCode-Best Time to Buy and Sell Stock III
- Linux搭建FTP服务器、配置和实现简单通过客户端连接的例子
- Android系统广播大全
- 应用 SAX 方式解析 XML
- 响应式web设计
- zForce红外触屏处理芯片驱动分析
- LeetCode-Best Time to Buy and Sell Stock III
- 2015年寒假总结
- 【转载】在jsp中调用报表IReport+JasperReport
- git clean
- SuspendThread、ResumeThread
- android 实现TextView实现跑马灯形式的字体
- 10招让你成为杰出的Java程序员
- Stm32F030用Coocox工程进行Bootloader升级时程序跑飞
- 每日时间表