题目

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).

Subscribe to see which companies asked this question

分析

紧接着121122 的另外一道题目,此次要求只能进行两次买卖交易,求最大利润。

一篇很好的分析文章,参考博客

第一步扫描,先计算出子序列[0,…,i]中的最大利润,用一个数组保存下来,那么时间是O(n)。

计算方法也是利用第一个问题的计算方法。

第二步是逆向扫描,计算子序列[i,…,n-1]上的最大利润,这一步同时就能结合上一步的结果计算最终的最大利润了,这一步也是O(n)。

第三步,求[0,i]的最大利润与[i,n-1]的最大利润之和的最大值,所以最后算法的复杂度就是O(n)的。

AC代码

class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.empty())
return 0; int n = prices.size(); vector<int> profits(n, 0), profits_reverse(n,0); //正向遍历,profits[i]表示 prices[0...i]内做一次交易的最大收益.
int low = prices[0] , cur_profit = 0;
for (int i = 1; i < n; ++i)
{
if (prices[i] < low)
{
low = prices[i];
}
else{
if (cur_profit < prices[i] - low)
cur_profit = prices[i] - low;
}
profits[i] = cur_profit;
}//for //逆向遍历, profits_reverse[i]表示 prices[i...n-1]内做一次交易的最大收益.
//当前最大价格
int high = prices[n - 1];
cur_profit = 0;
for (int i = n - 2; i >= 0; --i)
{
if (prices[i] > high)
high = prices[i];
else{
if (cur_profit < high - prices[i])
cur_profit = high - prices[i];
}//else
profits_reverse[i] = cur_profit;
} int max_profile = 0;
for (int i = 0; i < n; i++)
{
if ((profits[i] + profits_reverse[i]) > max_profile)
max_profile = profits[i] + profits_reverse[i];
}
return max_profile;
}
};

GitHub测试程序源码

最新文章

  1. entityframework学习笔记--007-实体数据建模基础之继承关系映射TPT
  2. The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. 错误的原因及解决方案
  3. [Surface] 在win8.1上使用QQ截图放大问题(解决办法)
  4. CentOS 6.7平台nginx压力测试(ab/webbench)
  5. Error : APP-FND-01926: The custom event WHEN-LOGON-CHANGED raised unhandled exception: ORA-06502: PL
  6. dfs和bfs的简单总结
  7. 如何在你的blog中添加炫酷的飘雪动画效果
  8. [HNOI 2010]Bus 公交线路
  9. [BJOI2019] 删数
  10. 如何在SpringBoot项目中使用拦截器
  11. php cli模式下获取参数的方法
  12. 如何更优雅地写Django REST framework
  13. KS检验学习[转载]
  14. NEST - How can i do multiple nested aggregation?
  15. Python学习---Python数据类型1206
  16. 5、RabbitMQ-订阅模式 Publish/Subscribe
  17. Python多重赋值
  18. python 内置函数eval()、exec()、compile()
  19. jquery获取含有某元素的的控件 “控件名[属性名=值]”
  20. Python的幂运算

热门文章

  1. 通过sqlserver sa密码修改windows操作系统密码
  2. IIS访问网站出错[要求输入用户名密码]的解决方案
  3. MVC3 自定义的错误页
  4. 记录下这周的mysql调优工作
  5. Random类、ThreadLocalRandom类
  6. Kendo MVVM 数据绑定(九) Text
  7. ABAP接口用法
  8. 帝国empirecms去除后台登陆认证码
  9. 【装载】删除Oracle11G
  10. Java 反射机制(一)