[LeetCode] 121 - Best Time to Buy and Sell Stock
2015-09-10 18:17
363 查看
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) {
int size = prices.size();
if (size <= 1) {
return 0;
}
int min_ = prices[0];
int res_ = prices[1] - prices[0];
for (int i = 2; i < size; ++i) {
min_ = min(prices[i-1], min_);
res_ = max(prices[i] - min_, res_);
}
return res_ < 0 ? 0 : res_;
}
};
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) {
int size = prices.size();
if (size <= 1) {
return 0;
}
int min_ = prices[0];
int res_ = prices[1] - prices[0];
for (int i = 2; i < size; ++i) {
min_ = min(prices[i-1], min_);
res_ = max(prices[i] - min_, res_);
}
return res_ < 0 ? 0 : res_;
}
};
相关文章推荐
- Android 控件 之 Menu 菜单
- ios 微信发送位置
- mysql 5.6的安装
- 淄博传统名菜——酥锅的做法
- QT学习之QString的arg方法
- nginx + ngx_lua安装测试
- 使用ListView应该注意的地方
- mysql max_allowed_packet 设置
- 淄博传统名菜——酥锅的做法
- 11.2.0.4添加节点时遇到ORA-12547: TNS:lost contact
- 使用ListView应该注意的地方
- 使用ListView应该注意的地方
- Pattern Examples
- 用JS获取地址栏参数的方法(超级简单)
- htm和ashx接收参数(附Mime 类型列表)
- JNI (一)、环境搭建
- .Net HttpPost的发送和接收示例代码
- hdu3506 Monkey Party
- mongoDB子文档列表更新
- Android - LayoutInflater