Best Time to Buy and Sell Stock III
来源:互联网 发布:你好万维网 知乎 编辑:程序博客网 时间:2024/05/16 14:35
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).
想不出来,网上搜了一个算法,从头算一遍,然后在从尾算一遍当前最大值,然后从不同的i分割,前后加起来最大的情况。另外还看到了一个求最大k次交易的一个通用算法,是根据一篇论文写出来的,看来学术确实能用到平常的编程里来,其实想想现在的二分查找等算法不都是以前的论文么。
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).
想不出来,网上搜了一个算法,从头算一遍,然后在从尾算一遍当前最大值,然后从不同的i分割,前后加起来最大的情况。另外还看到了一个求最大k次交易的一个通用算法,是根据一篇论文写出来的,看来学术确实能用到平常的编程里来,其实想想现在的二分查找等算法不都是以前的论文么。
int maxProfitIII(vector<int> &prices) {int len = prices.size();if (len == 0) return 0;vector<int> history(len, 0);vector<int> future(len, 0);int low = prices[0];for (int i = 1; i < len; i++){history[i] = max(history[i-1], prices[i] - low);low = min(low, prices[i]);}int high = prices[len-1];for (int i = len-2; i >= 0; i--){future[i] = max(future[i+1], high - prices[i]);high = max(high, prices[i]);} int maxProfit = 0; // 网上说第一次的卖和第二次的买可以在同一次,所以直接都是i相加就可以了for (int i = 0; i < len; i++){maxProfit = max(maxProfit, history[i] + future[i]);}return maxProfit;}
0 0
- 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
- Best Time to Buy and Sell Stock III
- 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
- Best Time to Buy and Sell Stock III
- 【leetcode】Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- LeetCode - Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock III
- 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
- 随机采样(Gibbs,MCMC)
- Android PackageManagerService分析二:安装APK
- LG智能耳机将于本周日在美国上市
- Lucene.Net 介绍
- Android Java中的static与final关键字的作用
- Best Time to Buy and Sell Stock III
- 自己的
- win2003安装IIS后的网站设置
- 浅谈ARM 汇编里的 literal pools(文字池)
- 从“假如有以下几种价格10,20,50,请你代码实现将他们排序输出”看设计模式中的策略模式
- 如果磁盘空间使用率大于60%就执行某个网页
- js中的函数参数个数问题(重载问题)
- 解决ViewPager双层嵌套的滑动问题
- cocos2dx 3.0 mac环境安装