方法:自我解法,存储最小的元素,然后用后面的减,若结果小于0,则将后面的存为最小的元素,每次得到大于0的数字则存储与下一个大于0的数字比较。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int temp = 0;
int max = 0;
temp = prices[0];
for(int i =1;i<prices.size();i++)
{
if(prices[i]-temp<0)
{
temp = prices[i];
}
else if (prices[i]-temp>0)
{
if(prices[i]-temp>max)
max = prices[i]-temp;
}
}
if (max<0)
return 0;
return max;
}
};