1. Best Time to Buy and Sell Stock

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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
Explanation: In this case, no transaction is done, i.e. max profit = 0.

解法1 暴力求解,计算出\(\max_{i < j} \{prices[j] - prices[i]\}\)

解法2 one-pass。在全局最低点买入,卖出一定在该点之后,因此一边寻找min_p,一边计算max_profit

class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
int profit = 0;
int min_p = INT_MAX;
for(int i = 0; i < n; ++i){
if(prices[i] < min_p)min_p = prices[i];
profit = max(profit, prices[i] - min_p);
}
return profit;
}
};

最新文章

  1. Zabbix监控VMare Vcenter
  2. json 与jsonp 特点及区别
  3. document获取节点byId&amp;byName
  4. 同时大量PPPoE连接请求,攻击PPPoE服务器,导致的用户异常掉线故障分析
  5. PHP生成CSV文件
  6. asm单机dg dbca报错ORA-01031 CRS-2676,rman restore主库控制文件报错ORA-15081
  7. 《C++ primer》--第12章
  8. nyoj 236 心急的C小加
  9. 洛谷 P1040 加分二叉树
  10. java获取对象属性类型、属性名称、属性值 【转】
  11. Java简介(2)-基本概念
  12. ios 判断屏幕显示是@2x还是@3x来调用字体大小
  13. 二维码神器QRCoder
  14. MySQL系列:数据库基本操作(1)
  15. 类对象序列化为json串,json串反序列化为类对象
  16. js 循环遍历数组
  17. 10_python_函数进阶
  18. Grunt 插件发布过程;
  19. Java基础89 MySQL存储过程
  20. CubieBoard 简单入门

热门文章

  1. py常用标准库
  2. JSR310-LocalDateTime序列化 &amp; 反序列化
  3. ubuntu web服务器配置
  4. visual studio c++项目文件分类混乱整理
  5. 【LeetCode】91. Decode Ways 解题报告(Python)
  6. D. Chloe and pleasant prizes
  7. 晴天小猪历险记之Hill(Dijkstra优先队列优化)
  8. 食物链(poj1182)
  9. Java编程基础
  10. TensorFlow.NET机器学习入门【7】采用卷积神经网络(CNN)处理Fashion-MNIST