problem

​121. Best Time to Buy and Sell Stock​

code

class Solution {
public:
int maxProfit(vector<int>& prices) {
int res = 0;
for(int i=0; i<prices.size(); i++)
{
int buy_price = prices[i];
for(int j=i+1; j<prices.size(); j++)
{
int sell_price = prices[j];
int tmp = sell_price - buy_price;
if(tmp>res) res = tmp;
}
}
return res;

}
};

one pass

class Solution {
public:
int maxProfit(vector<int>& prices) {
int min_price = INT_MAX;
int max_profit = 0;
for(int i=0; i<prices.size(); i++)
{
if(min_price> prices[i]) min_price = prices[i];
else if(prices[i]-min_price>max_profit) max_profit = prices[i]-min_price;
}
return max_profit;
}
};

 

参考

1. ​​Leetcode_Best Time to Buy and Sell Stock​​;