Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5 max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0 In this case, no transaction is done, i.e. max profit = 0.

分析

首先通过把相邻的股票价格相减得到一组差价,后面就转化成了最大子列和问题了;另外注意当传进来的prices的数组为空时,返回0;

class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()==0) return 0;
vector<int> profits(prices.size());
profits[0]=0;
for(int i=1;i<profits.size();i++)
profits[i]=prices[i]-prices[i-1];
int maxsum[profits.size()]={0},maxprofit=0;
for(int i=1;i<profits.size();i++){
maxsum[i]=max(profits[i],maxsum[i-1]+profits[i]);
maxprofit=max(maxprofit,maxsum[i]);
}
return maxprofit;
}
};

最新文章

  1. 绑定一个值给radio
  2. iOS推送原理
  3. nginx的优化
  4. AsyncTask和Handler对比(转)
  5. PHP输出缓冲(Output Buffering)
  6. 如何清除某条SQL的执行计划
  7. C++中static用法总结
  8. 对常量的引用(reference to const)的一般用途(转载)
  9. 关于c# 基础运算符的应用
  10. The Twelve-Factor App 实践
  11. 流量控制闸门——LimitLatch套接字连接数限制器
  12. ACM-ICPC 2018 徐州赛区网络预赛 H Ryuji doesn&#39;t want to study (树状数组差分)
  13. java ee Concurrency 并发编程
  14. k-近邻算法-手写识别系统
  15. Java连接数据库的driver和url写法
  16. Codeforces Round #516 (Div. 2) (A~E)
  17. 洛谷P1135 奇怪的电梯【bfs】
  18. Spring集成Solr搜索引擎
  19. poj 3984 -- 迷宫问题 深搜
  20. Educational Codeforces Round 44 (Rated for Div. 2)

热门文章

  1. 使iframe随内容(target到iframe的内容)改变而自适应高度,完美解决各种获取第一个demo高度后第二个高度不变情况
  2. 洛谷P2516 [HAOI2010]最长公共子序列
  3. Kubernetes 集群中使用 Helm 搭建 Spinnaker
  4. 同一个Tomcat下不同项目之间的session共享
  5. [App Store Connect帮助]三、管理 App 和版本(2.1)输入 App 信息:查看和编辑 App 信息
  6. [Swift通天遁地]九、拔剑吧-(13)创建页面的景深视差滚动效果
  7. 知识记忆1:标志寄存器PSW
  8. 使用Java生成word文档(附源码)
  9. python自动化测试学习笔记-6urllib模块&amp;request模块
  10. Python爬取贴吧中的图片