123. Best Time to Buy and Sell Stock III
来源:互联网 发布:淘宝客自动转换工具 编辑:程序博客网 时间:2024/06/10 03:45
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,我们求[0,i]与[i,n-1]两次收益,然后求和,遍历i,可以取其中的最大值,需要O(N^2)的时间。这样做时间超时了。
class Solution {public: int maxProfit(vector<int>& prices) { int n=prices.size(); if(n<2) return 0; int maxprofit=0; for(int i=0;i<n;i++) { int profit1=helper(prices,0,i); int profit2=helper(prices,i+1,n-1); if(maxprofit<(profit1+profit2)) maxprofit=profit1+profit2; } return maxprofit; } int helper(vector<int>& prices,int start,int end) { int n=end-start+1; if(n<2) return 0; int CurMin=prices[start]; int profit=0; for(int i=start;i<=end;i++) { CurMin=CurMin<=prices[i]?CurMin:prices[i]; profit=profit>=(prices[i]-CurMin)?profit:(prices[i]-CurMin); } return profit; }};
第二种方法是动态规划:用两个数组,第一个数组f1[i]用来表示在[0,i]内进行买入卖出的最大收益,用f2[i]表示在[i,n-1]内进行买入卖出的最大收益,然后最大收益即为max(f1[i]+f2[i])。
class Solution {public: int maxProfit(vector<int>& prices) { int n=prices.size(); if(n<2) return 0; vector<int>profit1(n,0); vector<int>profit2(n,0); int minprice=prices[0]; for(int i=1;i<n;i++) { minprice=min(minprice,prices[i]); profit1[i]=max(profit1[i-1],prices[i]-minprice); } int maxprice=prices[n-1]; for(int i=n-2;i>=0;i--) { maxprice=max(prices[i],maxprice); profit2[i]=max(profit2[i+1],maxprice-prices[i]); } int maxprofit=0; for(int i=0;i<n;i++) maxprofit=max(maxprofit,profit1[i]+profit2[i]); return maxprofit; }};
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
- 面试与简历那些事
- 取整小数
- Ubuntu 16.10 64位安装WPS
- 史上最全Java学习视频下载地址分享
- 水平/垂直滚动联动
- 123. Best Time to Buy and Sell Stock III
- 为什么eclipse不识别HttpServlet
- gevent+request+novel项目笔记
- Java代码实现多线程下载和断点续传
- leetcode刷题之旅——121. Best Time to Buy and Sell Stock
- SQL一些常见的查询练习
- 自动化运维工具ansible的使用详细教程
- Spring Mvc开发遇到的问题汇总
- 图解正向代理、反向代理、透明代理