121. Best Time to Buy and Sell Stock
2016-06-30 13:09
288 查看
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.size() == 0) return 0;
int low = prices[0];
int ans = 0;
for(int i=1; i<prices.size(); i++){
if(prices[i] < low) low = prices[i];
else if(prices[i] - low > ans) ans = prices[i] - low;
}
return ans;
}
};
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.
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)
不做无用功,遍历一次即可更新当前最小售价及最大利润。
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() == 0) return 0;
int low = prices[0];
int ans = 0;
for(int i=1; i<prices.size(); i++){
if(prices[i] < low) low = prices[i];
else if(prices[i] - low > ans) ans = prices[i] - low;
}
return ans;
}
};
相关文章推荐
- 1-3数据模型
- CentOS6.3升级openssl和openssh
- hdu 4536 XCOM Enemy Unknown(搜索)
- nagios邮件告警设置方法成功版本
- Xcode7 安装VVDocumenter-Xcode步骤
- Python学习笔记
- asp.net MD5 加密
- [第三方工具]利用第三方工具xPort导出Excel文件
- 1-2数据库管理技术
- 『零行代码』解决键盘遮挡问题(iOS)
- 离婚后感言
- 执行SVN cleanup 反复失败
- hdu 4544 湫湫系列故事——消灭兔子(贪心,优先队列)
- 1-1数据库系统相关概念
- server2008服务器IIS7 +PHP5.3出现500错误的排错方法
- swiper的基础教程(十二)
- 4最短路径之村庄4
- sql语句技巧--插入时间时非必填的情况
- Android Studio根据apk获取Sha1值
- [阶段总结一]感悟