Best Time to Buy and Sell Stock
2015-09-04 21:02
260 查看
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 share = 0;
int min = prices[0];
int max = prices[0];
for(int i = 1; i < prices.size(); ++ i)
{
if(prices[i] >= max)
{
max = prices[i];
if(share <= (max - min))
{
share = max - min;
}
}
if(prices[i] < min)
{
min = prices[i];
max = prices[i];
}
}
return share;
}
};
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 share = 0;
int min = prices[0];
int max = prices[0];
for(int i = 1; i < prices.size(); ++ i)
{
if(prices[i] >= max)
{
max = prices[i];
if(share <= (max - min))
{
share = max - min;
}
}
if(prices[i] < min)
{
min = prices[i];
max = prices[i];
}
}
return share;
}
};
相关文章推荐
- Java web 学习
- 电脑 右击 发送到没有桌面快捷方式解决方法
- Caffe学习:使用pycaffe定义网络
- NDK开发之数组操作
- NDK开发之数组操作
- 解读为什么有符号的char可表示范围是-128~+127
- LeetCode || Ugly Number
- Android Api Demos登顶之路(五十六)Service Remote Service
- NDK开发之数组操作
- NDK开发之数组操作
- nginx主配置文件 在那找怎么打开
- @+id/android:list"的写法
- json解析中的坑+解析方法
- 深入理解HTTP Session
- Stanford机器学习---第四讲. 神经网络的表示 Neural Networks representation
- python 迭代、Iterable(可迭代)对象的判断和内置函数enumerate的使用
- 乘积最大子序列
- Drillbench Cemcalc v3.9 1CD(动态固井设计分析软件)/Drillbench Suite v6.1 1CD(钻井作业设计及规划软件)
- Linux文件系统上的特殊权限(SUID、SGID、Sticky)的知识点
- django 1.8 官方文档翻译: 3-5-2 使用Django输出PDF