class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices == nullptr || prices.size() < 1)
return 0;
int max_profit = 0;
for( int i = 0; i < prices.size() ; ++i){
for(int j = i+1;j<prices.size(); ++j)
if(prices[j] - prices[i] > max_profit)
max_profit = prices[j] - prices[i];
}
return max_profit;
}
};
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices == nullptr || prices.size() < 1)
return 0;
int max_profit = 0;
int min = prices[0];
for( int i = 1; i < prices.size() ; ++i){
if(min > prices[i]) min = prices[i];
if(max_profit < prices[i] - min) max_profit = prices[i]-min;
}
return max_profit;
}
};
维护min来加快速度,一遍循环。