这个题没想到怎么用动态规划,就暴力了,然后超时了,这是我超时了的代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int maxprofit = 0;
vector<int> profit(prices.size());
for(int i = 0; i < prices.size(); ++i)
{
int max = 0;
for(int j = i+1; j < prices.size(); ++j)
{
if(prices[j] - prices[i] > max)
max = prices[j] - prices[i];
}
profit[i] = max;
if(profit[i] > maxprofit)
maxprofit = profit[i];
}
return maxprofit;
}
};
看了别人的思路之后,明白这个题动态规划的点在于,我只需要用当前这个点的费用减去这个点之前的最小费用,就是这个点卖出时候的最大收益。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int minprice = INT_MAX;
int maxpro = 0;
for(int i = 0; i < prices.size(); ++i)
{
minprice = min(minprice, prices[i]);
maxpro = max(maxpro, prices[i] - minprice);
}
return maxpro;
}
};