核心思想:前i天的最大收益=max{前i-1天的最大收益,第i天的价格-前i-1天中的最小价格}
暴力求解的方法:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int max = 0;
int tmp = 0;
for(int i = 0;i<prices.size();++i)
{
for(int j = i;j<prices.size();++j)
{
tmp = prices[j] - prices[i];
if(max < tmp)
max = tmp;
}
}
return max;
}
};
巧妙地解法:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int min = INT_MAX;
int max_profit = 0;
for(auto e = prices.begin();e != prices.end();++e)
{
if(*e < min)
min = *e;
max_profit = max(max_profit,*e-min);
}
return max_profit;
}
};