LeetCode OJ 之 Best Time to Buy and Sell Stock (买卖股票的最佳时间)
来源:互联网 发布:csol雷神2016数据 编辑:程序博客网 时间:2024/04/20 09: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。
假设有一个数组,第i个元素是一个第i天的股票的价格。
如果你只被允许完成最多一次交易(即只能买一次和卖一次股票),设计一个算法,找出最大的利润。
核心思想请参看:最大子数组问题
代码1:
class Solution {public: int maxProfit(vector<int> &prices) { //思路:求出每相邻两天的收益,连续n个相邻两天收益最大的即可获得最大利润。核心思想是求最大子数组问题 vector<int> ivec;//存储prices内前后数之差,即相邻两天股票收益 if(prices.size() == 0) return 0; ivec.push_back(0);//首天收益为0 for(vector<int>::iterator iter1 = prices.begin() ; iter1 != prices.end()-1 ; iter1++) { ivec.push_back(*(iter1 + 1) - *iter1);//把相邻两天的股票收益存入ivec } //下面是求数组中,子数组中和最大的,实质是求股票的最大收益 int preSum=0,curSum=0;//pre是之前保存的子数组元素和最大的,cur保存当前子数组和最大的 for(vector<int>::iterator iter2 = ivec.begin() ; iter2 != ivec.end() ; iter2++) { curSum += *iter2; if(preSum <= curSum)//如果之前保存的最大值比当前的最大值小,则替换掉 preSum = curSum; if(curSum <= 0)//如果当前最大收益<=0,则没有保存的必要了,重新计算后面的 curSum = 0; } return preSum; }};
代码2:
class Solution {public: int maxProfit(vector<int> &prices) { //思路:分别找到价格最低和最高的一天,低进高出,最低的要在最高前 if (prices.size() < 2) return 0; int profit = 0; //当前最大收益 int cur_min = prices[0]; // 当前最低股票价 for (int i = 1; i < prices.size(); i++) { cur_min = min(cur_min, prices[i]);//遍历到当前的最低股价 profit = max(profit, prices[i] - cur_min);//当前价格-最低价得到的收益和之前保存的最大收益指,取较大者 } return profit; }};
0 0
- LeetCode OJ 之 Best Time to Buy and Sell Stock (买卖股票的最佳时间)
- [LeetCode] Best Time to Buy and Sell Stock IV 买卖股票的最佳时间之四
- LeetCode OJ 之 Best Time to Buy and Sell Stock II (买卖股票的最佳时间 2)
- LeetCode OJ 之 Best Time to Buy and Sell Stock III (买卖股票的最佳时间 - 三)
- LeetCode-121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)
- Best Time to Buy and Sell Stock 【最佳买卖股票的时间】【容易】
- 122. Best Time to Buy and Sell Stock II 最佳买卖股票的时间
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】
- 121. Best Time to Buy and Sell Stock 最佳买卖股票时间
- Best Time to Buy and Sell Stock II 最佳时间买入卖出股票(多次买卖)@LeetCode
- Best Time to Buy and Sell Stock III 最佳时间买入卖出股票(最多两次买卖)@LeetCode
- LeetCode 121 Best Time to Buy and Sell Stock(股票买入卖出的最佳时间)
- [LeetCode]122. Best Time to Buy and Sell Stock II(最佳买卖时间 II)
- Best Time to Buy and Sell Stock 买卖股票最好的时间
- Best Time to Buy and Sell Stock II 买卖股票最好的时间II
- Best Time to Buy and Sell Stock III 买卖股票的最好时间
- Best Time to Buy and Sell Stock 买卖股票的最好时间
- [leetcode 121] Best Time to Buy and Sell Stock---只能买卖股票一次的最大收益
- PROJECT 04-04
- 使用ExtJS三个月小结--开发小白
- 第十一周项目六——1000以内的回文素数
- linux操作
- PROJECT 04-05
- LeetCode OJ 之 Best Time to Buy and Sell Stock (买卖股票的最佳时间)
- 利用typedef定义函数指针类型
- Head First---装饰者模式
- P/NP问题
- 【图像处理】基于OpenCV底层实现的滤波
- PAT 1034. Head of a Gang (30)
- 第十二周项目三—递归函数十进制转二进制
- 帮同学写的一个简单地随机数学题生成程序,非常简单,适合练手
- 以figure 4.4为例检验谱平面随着图像旋转而旋转的性质