123.Best Time to Buy and Sell Stock III
来源:互联网 发布:哪种编程语言最厉害 编辑:程序博客网 时间:2024/06/09 13:44
题意:用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。最多交易两次,手上最多只能持有一支股票,求最大收益。
可以在整个区间的每一点切开,然后分别计算左子区间和右子区间的最大值,然后再用O(n)时间找到整个区间的最大值。
看来以后碰到与2相关的问题,一定要想想能不能用二分法来做!
下面复制pickless的讲解,我觉得我不能比他讲的更好了
O(n^2)的算法很容易想到:
找寻一个点j,将原来的price[0..n-1]分割为price[0..j]和price[j..n-1],分别求两段的最大profit。
进行优化:
对于点j+1,求price[0..j+1]的最大profit时,很多工作是重复的,在求price[0..j]的最大profit中已经做过了。
类似于Best Time to Buy andSell Stock,可以在O(1)的时间从price[0..j]推出price[0..j+1]的最大profit。
但是如何从price[j..n-1]推出price[j+1..n-1]?反过来思考,我们可以用O(1)的时间由price[j+1..n-1]推出price[j..n-1]。
最终算法:
数组l[i]记录了price[0..i]的最大profit,
数组r[i]记录了price[i..n]的最大profit。
已知l[i],求l[i+1]是简单的,同样已知r[i],求r[i-1]也很容易。
最后,我们再用O(n)的时间找出最大的l[i]+r[i],即为题目所求。
public class Solution { public int maxProfit(int[] prices) { if(prices.length<=0){ return 0; } int len = prices.length; int[] left = new int[len]; int[] right = new int[len]; int leftMin = prices[0]; int leftMax = 0; for (int i=0 ; i<len; i++){ leftMin = Math.min(leftMin,prices[i]); leftMax = Math.max(leftMax,prices[i]-leftMin); left[i]=leftMax; } // System.out.println(Arrays.toString(left)); int rightMax = 0; int rightMaxNum = prices[len-1]; for(int j = len-2; j>=0;j--){ rightMaxNum = Math.max(rightMaxNum,prices[j]); rightMax = Math.max(rightMax,rightMaxNum - prices[j]); right[j] = rightMax; } // System.out.println(Arrays.toString(right)); int result = 0; for(int k =0;k<len;k++){ result = Math.max(result,right[k]+left[k]); } return result; }}
0 0
- LeetCode 123. Best Time to Buy and Sell Stock III
- 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] 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] 123. Best Time to Buy and Sell Stock III
- 123. Best Time to Buy and Sell Stock III
- 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
- 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 123. Best Time to Buy and Sell Stock III
- 用word2016 写CSDN 博客
- linux中wget 、apt-get、yum rpm区别
- vmware虚拟机硬盘空间扩展---解决ubuntu空间不够用的问题
- 项目笔记2
- laravel添加跨平台检测功能
- 123.Best Time to Buy and Sell Stock III
- C语言 创建一个数组 实现函数init()初始化数组 empty()清空数组 reverse()逆置数组
- eval() 与 js 解析JSON报错
- 解决Eclipse闪退问题的几种方案总结
- linux安装mysql 5.6.33
- 高速抓包平台过滤功能分析
- redis 数据类型详解 以及 redis适用场景场合
- Android音视频点/直播模块开发知识总结-1
- 浅谈android中手机联系人字母索引表的实现