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.

Invariant 在于,如果第i 天和第j 天分别是最高收益的买入点和卖出点,那么prices[i] 必然是[0, j] 区间内价格的最低点。

只用遍历一次,用当前找到的最低价格来计算收益,并更新收益最大值,同时更新价格最低点。遍历完成之后即得结果。

/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
var n = 0;
var lowest = prices[0];
prices.forEach(function(p) {
n = Math.max(n, p - lowest);
lowest = Math.min(lowest, p);
});
return n;
};

最新文章

  1. SharePoint Backup
  2. 坚持不懈之linux haproxy 配置文件 详情
  3. ACM题目————还是畅通工程
  4. two Sum ---- LeetCode 001
  5. HDU5715 XOR 游戏 二分+字典树+dp
  6. 在多个linux服务器上执行一个命令
  7. MIME 部分扩展名与类型对应
  8. 白帽子讲Web安全1.pdf
  9. 1002. 写这个号码 (20)(数学啊 ZJU_PAT)
  10. C#外挂QQ
  11. 简单搭建iOS开发项目框架
  12. Mysql常用30种SQL查询语句优化方法
  13. 带着萌新看springboot源码02
  14. TF-IDF特征选择
  15. python note 09 初识函数
  16. Jython 安装使用
  17. Best Chrome Extensions
  18. Map、Set、List集合差别及联系详解
  19. yii 缓存的使用 以及使用需要开启php的apc扩展
  20. 自己的reset.css

热门文章

  1. android 图像处理系列合集
  2. gulp实现打包js/css/img/html文件,并对js/css/img文件加上版本号
  3. 聊聊HTTPS和SSL/TLS协议
  4. 这些年MAC下我常用的那些快捷键
  5. <<< eclipse软件部署修改项目的访问地址
  6. Android内存优化-内存泄漏的几个场景以及解决方式
  7. Linux系统概述
  8. JointBoost+CRF+GraphCut做手绘草图的分割
  9. html5 新选择器 querySelector querySelectorAll
  10. 【09-04】java内部类学习笔记