Best Time to Buy and Sell Stock III
来源:互联网 发布:精易编程助手 下载 编辑:程序博客网 时间:2024/06/05 16:06
题目:
Say you have an array for which the ith element is the price of a given stock on dayi.
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).
第一道:
if(prices.size()<=1) return 0; int low = prices[0]; vector<int> maxpro; int max = 0; maxpro.push_back(0); for(int j=1;j<prices.size();j++) { int tmp = prices[j]-low; if(tmp > max) max = tmp; if(prices[j]<low) low = prices[j]; maxpro.push_back(max); } int result = maxpro[prices.size()-1];
这里并不是将第二道题中的最大的两个局部利润值相加得到结果。这样是不对的。
我们知道:对于两个利润值中的单个的利润值,并不一定是一个递增序列所对应的max-min,可能是如第一题一样计算0~i之间的最大利润。
对于第二个利润值,则计算i+1~n-1之间的利润最大值。两者相加得到结果。
既然最多只能完成两笔交易,而且交易之间没有重叠,那么就divide and conquer。
设i从0到n-1,那么针对每一个i,看看在prices的子序列[0,...,i][i,...,n-1]上分别取得的最大利润(第一题的函数)即可。
这样初步一算,时间复杂度是O(n2)。
动态规划:
那就是第一步扫描,先计算出子序列[0,...,i]中的最大利润,用一个数组保存下来,那么时间是O(n)。
第二步是逆向扫描,计算子序列[i,...,n-1]上的最大利润,这一步同时就能结合上一步的结果计算最终的最大利润了,这一步也是O(n)。
所以最后算法的复杂度就是O(n)的。
具体实现:
class Solution {public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function if(prices.size()<=1) return 0; int low = prices[0]; vector<int> maxpro; int max = 0; maxpro.push_back(0); for(int j=1;j<prices.size();j++) { int tmp = prices[j]-low; if(tmp > max) max = tmp; if(prices[j]<low) low = prices[j]; maxpro.push_back(max); } int result = maxpro[prices.size()-1]; int high = prices[prices.size()-1]; max = 0; for(int j=prices.size()-2;j>=0;j--) { int tmp = high-prices[j]; if(tmp>max) max = tmp; if(prices[j]>high) high = prices[j]; if(maxpro[j]+max>result) result = maxpro[j]+max; } return result; }};
- 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
- ThinkPHP无限分类
- What is Index and how it works in SQL Server?
- spring应用proxool连接池,关于spring相关配置,proxool配置是上篇
- 如何查看window 端口占用情况
- MySQL EXPLAIN 命令详解学习
- Best Time to Buy and Sell Stock III
- java.sql.SQLException: ORA-01858: 在要求输入数字处找到非数字字符
- 我的心情
- MTK boot.img recover.img 解压和压缩工具下载地址
- 谈大同世界
- lspci
- 使用SimpleCursorAdapter
- Qt生产者消费者实验:等待条件QWaitCondition
- [沧海拾遗]applet本地web开发例子