本文主要是介绍代码随想录算法训练营第四十九天| 121 买卖股票的最佳时机 122 买卖股票的最佳时机 ||,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录
121 买卖股票的最佳时机
122 买卖股票的最佳时机 ||
121 买卖股票的最佳时机
class Solution {
public:int maxProfit(vector<int>& prices) {int res = 0;int now = prices[0];for(int i = 1;i < prices.size();i++){if(prices[i] > now){res = max(res,prices[i] - now);}now = min(now,prices[i]);}return res;}
};
时间复杂度O(n)
空间复杂度O(1)
122 买卖股票的最佳时机 ||
class Solution {
public:int maxProfit(vector<int>& prices) {int res = 0;int now = prices[0];for(int i = 1;i < prices.size();i++){if(prices[i] > now)res += prices[i] - now;now = prices[i];}return res;}
};
时间复杂度O(n)
空间复杂度O(1)
这篇关于代码随想录算法训练营第四十九天| 121 买卖股票的最佳时机 122 买卖股票的最佳时机 ||的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!