[LeetCode] Best Time to Buy and Sell Stock
Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
解题思路:
题意为给定股票每一个时间点的价格,且规定仅仅能买卖一次,问可以赚的最多的钱是多少。
记录当前为止最小的股价,然后当前股价与当前最小股价之差大于当前最大利润。则更新最大利润就可以。
class Solution { public: int maxProfit(vector<int>& prices) { int len = prices.size(); if(len==0 || len==1){ return 0; } int maxProfit = 0; int minPrices = prices[0]; for(int i=1; i<len; i++){ minPrices = min(minPrices, prices[i]); maxProfit = max(maxProfit, prices[i] - minPrices); } return maxProfit; } };
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步