?題目鏈接:121. 買賣股票的最佳時機(jī) - 力扣(Leetcode)
?
分析:這里的數(shù)據(jù)大小為1e5,所以使用暴力會TLE.文章來源:http://www.zghlxwxcb.cn/news/detail-406470.html
思路:我們發(fā)現(xiàn),需要找到最大利潤,其目標(biāo)就是找到當(dāng)前第i位后的最大值。換位思考,就是找到當(dāng)前第i位前的最小值。文章來源地址http://www.zghlxwxcb.cn/news/detail-406470.html
代碼:
class Solution {
public:
int maxProfit(vector<int>& prices) {
const int INF=1e9+10;
int minn=INF,maxx=0;
for(auto x:prices){
maxx=max(maxx,x-minn);
minn=min(minn,x);
}
return maxx;
}
};
到了這里,關(guān)于[思維]LeetCode:121.買賣股票的最佳時機(jī)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!