这道题需要用一个变量记录前面股票中价格最低的那个(lowest),然后看当前股票与lowest之差是多少,求出这些差中最大的那个。
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.size() == 0)
{
return 0;
}
int maxp = 0, p, lowest = prices[0];
for (int i = 1; i < prices.size(); ++i)
{
if (prices[i] < lowest)
{
lowest = prices[i];
}
else if (prices[i] - lowest > maxp)
{
maxp = prices[i] - lowest;
}
}
return maxp;
}
};
int main()
{
std::vector<int> prices;
prices.push_back(1);
prices.push_back(2);
Solution s;
cout<<s.maxProfit(prices)<<endl;
return 0;
}