331-Leetcode 买卖的股票的最佳时机

在这里插入图片描述
方法一:暴力法

两次for循环,一个一个比较,找出最大利润

class Solution 
{
public:
	int maxProfit(vector<int>& prices) 
	{
		int len = prices.size();
		int max_profit = 0;
		for (int i = 0; i < len; ++i)
		{
			for (int j = i + 1; j < len; ++j)
			{
				max_profit = max(max_profit, prices[j] - prices[i]);
			}
		}
		return max_profit;
	}
};
int main()
{
	Solution A;
	vector<int> ve{ 7,1,5,3,6,4 };
	cout << A.maxProfit(std::ref(ve)) << endl;
	return 0;
}

时间复杂度:O(n^2),循环运行 n(n+1)/2 次
空间复杂度:O(1),只使用了常数个变量

方法二:一次遍历

记录历史最低价格 min_price,我们就可以假设自己的股票是在那天买的那么我们在第 i 天卖出股票能得到的利润就是 prices[i] - min_price

class Solution 
{
public:
	int maxProfit(vector<int>& prices) 
	{
		int len = prices.size();
		int max_profit = 0;
		int min_price = INT_MAX;
		for (auto x:prices)
		{
			max_profit = max(max_profit, x - min_price);
			min_price = min(min_price, x);
		}
		return max_profit;
	}
};
int main()
{
	Solution A;
	vector<int> ve{ 7,1,5,3,6,4 };
	cout << A.maxProfit(std::ref(ve)) << endl;
	return 0;
}

时间复杂度:O(n),只需要遍历一次
空间复杂度:O(1),只使用了常数个变量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值