简单粗暴的第一种解法:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int m = prices.size();
int maxprofit = 0;
for (int k = 0; k < m; k++)
{
for (int i = k; i < m; i++){
if (prices[i] - prices[k] > maxprofit)
maxprofit = prices[i] - prices[k];
}
}
return maxprofit;
}
};
第二种解法:
从最后一个元素开始遍历(vector不能为空),维持一个最大价格和一个最大收益
class Solution {
public:
int maxProfit(vector<int>& prices) {
int m = prices.size();
if (m == 0) return 0;
int maxprofit = 0;
int maxprice = prices.back();
for (int k = m-1; k >= 0; k--)
{
if (prices[k] > maxprice) maxprice = prices[k];
else if(maxprice - prices[k] > maxprofit) maxprofit = maxprice - prices[k];
}
return maxprofit;
}
};