Best Time to Buy and Sell Stock
来源:互联网 发布:json中汉字乱码 编辑:程序博客网 时间:2024/05/16 16:21
题目:
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.
思想:1. 因为只可以交易一次,所以可以看成求数组的最大差(注意:先买后卖,所以只可能是后面的数减去前面的数);
2. 为了程序不超时,先求出极值(局部最大和最小值),放在vector中
代码:
class Solution {public: int maxProfit(vector<int> &prices) { vector<int> result; int j = 0; int max_dis = 0; int n = prices.size(); while(j < n) { while(j+1 < n && prices[j] >= prices[j+1]) j++; if(j < n-1) { result.push_back(prices[j]); j++; while(j+1 < n && prices[j] <= prices[j+1]) j++; result.push_back(prices[j]); } j++; } int sz = result.size(); for(int i = 0; i < sz-1; i += 2) { for(int j = i+1; j < sz; j += 2) { int tmp = result[j] - result[i]; if(tmp > max_dis) max_dis = tmp; } } return max_dis;}};
上面第一次实现的比较复杂。
参考http://blog.csdn.net/pickless/article/details/12033745
使用cur_min表示之前股票的最低价,max_profit表示当前的股票最大利益
class Solution {public: int maxProfit(vector<int> &prices) { if(prices.size() == 0) return 0; int max_profit = 0, cur_min = prices[0]; for(int i = 1; i < prices.size(); i++) { int tmp = prices[i] - cur_min; if(tmp > max_profit) max_profit = tmp; if(prices[i] < cur_min) cur_min = prices[i]; } return max_profit;}};
0 0
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- 各种字符串Hash函数比较
- 幂取模算法
- cmake的使用笔记
- java输入输出--I/O操作基础知识学习
- java开源微博系统weibo4j分享
- Best Time to Buy and Sell Stock
- CSS中设置图片的宽度和高度
- 图解JVM内存模型
- error:unresolved external symbol __imp__curl_easy_cleanup
- android 画图之setXfermode 处理两图相交叉的情况
- AppKey和AppSecret的关系
- log file sync P1 P2 P3
- C++参数传递方式
- 关于Xcode下编译突然造成硬盘消耗十几G的问题