//2014年8月26日13:55:48
//2014年8月26日14:12:22
//从前向后遍历一次,记录截止到目前的最低价,计算可能受益,更新最大受益,更新最低价
//出错点是:受益为负值时返回0
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.size() <= 1){
return 0;
}
int tempMin = prices[0],tempMax = 0;//tempMax初始为0较好,不会出现负值结果
for(vector<int>::size_type i=1 ; i<prices.size() ; i++){
if(prices[i]-tempMin>tempMax){
tempMax = prices[i]-tempMin;
}
if(prices[i] < tempMin){
tempMin = prices[i];
}
}
return tempMax;
}
};
int main()
{
int p[] = {3,2,6,5,0,3};
vector<int> prices(p,p+6);
Solution S;
cout << S.maxProfit(prices) << endl;
return 0;
}
【leetcode】best-time-to-buy-and-sell-stock
最新推荐文章于 2019-05-01 17:41:02 发布