leetcode 121. Best Time to Buy and Sell Stock
2016-03-31 15:42
197 查看
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.
int maxProfit(int* prices, int pricesSize) {
if (prices == NULL)
return 0;
if (pricesSize < 2)
return 0;
int max = 0;
int k = 0;
while (k + 1 < pricesSize)
{
while (k + 1 < pricesSize&&prices[k] > prices[k + 1])
k++;
int kk = k;
while (kk + 1 < pricesSize&&prices[kk + 1] >= prices[k])
{
if (prices[kk + 1] - prices[k] > max)
max = prices[kk + 1] - prices[k];
kk++;
}
k = kk;
}
return max;
}
accepted
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.
int maxProfit(int* prices, int pricesSize) {
if (prices == NULL)
return 0;
if (pricesSize < 2)
return 0;
int max = 0;
int k = 0;
while (k + 1 < pricesSize)
{
while (k + 1 < pricesSize&&prices[k] > prices[k + 1])
k++;
int kk = k;
while (kk + 1 < pricesSize&&prices[kk + 1] >= prices[k])
{
if (prices[kk + 1] - prices[k] > max)
max = prices[kk + 1] - prices[k];
kk++;
}
k = kk;
}
return max;
}
accepted
相关文章推荐
- js表单验证实例讲解
- js数组去重
- MATLAB批量读取一个文件夹里的图像
- mysql悲观锁总结和实践
- 5.5.3使用terminfo功能标志
- 实验六:分析Linux内核创建一个新进程的过程
- js中的问题(this)(遍历对象中的属性)
- JAVA Web.xml 加载顺序
- Adb connection Error:远程主机强迫关闭了一个现有的连接
- 笔记本有线网卡未识别无法获取IP地址
- 使用mjrefresh遇到的坑爹bug
- 获取URL内容
- phonegap上传及后台springmvc接收文件
- 高德地图内存测试报告
- phpcms文件目录结构
- MFC——10.网络编程基础
- HDU 3887 Counting Offspring(dfs序+树状数组)
- DSP28335 ecap使用
- https://和http://区别
- Android开源项目分类汇总(五)ColorPickView、GraphView、UI Style