题意很明确,在只允许一次买入与售出事务中找到最大利润。
有两点需要注意:
1,只允许一次事务
2,售出时间必须在买进之后
代码(Time Limit Exceeded)
class Solution {
public:
int maxProfit(vector<int> &prices) {
int max = 0;
for(int i = 0; i < prices.size(); ++i)
{
for(int j = i ; j < prices.size(); ++j)
{
if(prices[i]-prices[j]>max)
max = prices[i]-prices[j];
}
}
return max;
}
};
算法时间复杂度为O(n^2), 提交后提示超时.
分析:
上述算法是从前往后执行,即尝试确定买入时间再遍历找到售出时间
若要降低复杂度,可以从后往前执行,即找到最大的售出时间,该售出时间即为全局最优
代码(Accepted)
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.size()==0)
return 0;
int maxNum = 0;
int maxSold = prices[prices.size()-1];
for(int i = prices.size()-1; i >= 0; --i)
{
maxSold = max(maxSold, prices[i]);
maxNum = max(maxNum, maxSold - prices[i]);
}
return maxNum;
}
};