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.

思路:注意不能简单地将最大值-最小值。卖必须发生在买之后,最小值得在最大值之前。记录下到当前为止最小值。

class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.empty()) return ;
int maxProfit = ;
int min = INT_MAX;
int profit; for(vector<int>::iterator it = prices.begin(); it < prices.end(); it ++)
{
if ((*it)<min)
{
min = *it;
}
else
{
profit = *it - min;
if(profit > maxProfit)
{
maxProfit = profit;
}
}
}
return maxProfit;
}
};

最新文章

  1. spring boot启用tomcat ssl
  2. (转)提高mysql千万级大数据SQL查询优化30条经验(Mysql索引优化注意)
  3. encfs创建时fuse: failed to exec fusermount: Permission denied错误解决
  4. opencv学习笔记(05)——操作相邻区域
  5. 纯tarjan poj2186
  6. javascript之数据推送
  7. PHP PDO 简单登陆操作
  8. html中行内元素与块级元素的区别。
  9. HDU 5795 A Simple Nim
  10. webpack-react之webpack篇(http://www.jianshu.com/p/794d573d2c53)
  11. EM算法原理总结
  12. [HNOI2009]通往城堡之路
  13. RabbitMQ入门:认识并安装RabbitMQ(以Windows系统为例)
  14. Redis 配置内容总结
  15. mongo 的导入和导出
  16. phpcms网页替换验证码功能 及 搜索功能
  17. vmware 里MAC 鼠标能移动 无法单击
  18. ZOJ2836-Number Puzzle-容斥原理
  19. db2 查询表前几行
  20. [转]web高级开发的成长之路

热门文章

  1. java web 程序---javabean代码,出现错误。奇怪,无法解释的运行问题
  2. [转]判断是否 Win7 且需要管理员权限
  3. 1061 Dating (20 分)
  4. java 为什么wait(),notify(),notifyAll()必须在同步方法/代码块中调用?
  5. Oracle 某字段值相同的取前几条数据
  6. Windows环境下多版本JDK切换
  7. 从线性回归到CNN【转】
  8. Ubuntu16.04或18.04上安装QQ微信迅雷
  9. 【C++11新特性】 nullptr关键字
  10. 常用数据库1 sqlserver