Best Time to Buy and Sell Stock III -- Leetcode
来源:互联网 发布:大作家写作软件多少钱 编辑:程序博客网 时间:2024/05/22 10:46
12.25 2014
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).
class Solution {public: int maxProfit(vector<int> &prices) { int day=prices.size(); if(day<2) return 0; int Max=0; int Max1=0; int Max2=0; int lowest=prices[0]; for(int i=0;i<day;i++){ Max1=helper(prices,0,i); Max2=helper(prices,i+1,day-1); Max=max(Max1+Max2,Max); } return Max; } int helper(vector<int> &prices, int start, int end){ int profit=0; int lowest=prices[start]; for(int i=start;i<=end;i++){ profit=max(prices[i]-lowest,profit); lowest=min(lowest,prices[i]); } return profit; }};
做法一:拆成两段,对两段分别求最大和,加起来的和取最大值即为答案。但是会出现超时。
class Solution {public: int maxProfit(vector<int> &prices) { int day=prices.size(); if(day<2) return 0; vector<int> v(day,0); vector<int> p(day,0); for(int i=1, valley=prices[0];i<day;i++){ valley=min(valley,prices[i]); v[i]=max(v[i-1],prices[i]-valley); } for(int i=day-2, peak=prices[day-1];i>=0;i--){ peak=max(peak,prices[i]); p[i]=max(p[i],peak-prices[i]); } int profit=0; for(int i=0;i<day;i++) profit=max(profit,v[i]+p[i]); return profit; }};
做法二:
稍微有些不同,主要是在代码上的区别,空间和时间上的tradeoff,把各种可能先算一遍存在vector内然后再进行求最大值。
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
- [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
- select 操作
- 第二十二章 集成验证码——《跟我学Shiro》
- strtol,strtoul,strtod .
- Android apk包反编译与重打包签名
- 近期要读的书
- Best Time to Buy and Sell Stock III -- Leetcode
- javascript 左右 或者上下翻滚效果
- 塔和精灵的创建
- OSGi使用四问
- 向Sql Server数据库中导入固定格式的txt文本数据
- opencv中的图片对象显示在mfc控件中
- 收藏的一些代码片段(持续更新)
- NLP谢道思亲子教育:如何把教育孩子这件事变得更简单
- Android中 崩溃异常的处理