leet_121_ maxProfit(股票收益最大化1)

本文介绍了一种寻找股票买卖最大利润的算法。该算法通过遍历价格数组,记录最低购买价格和最高利润,最终返回最大可能利润。示例展示了算法在不同价格序列上的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 问题描述:假设你有一个数组,其中第 i 个元素是一支给定股票第 i 天的价格。
    如果您只能完成最多一笔交易(即买入和卖出一股股票),则设计一个算法来找到最大的利润。

  • 示例1:

    • Input: [7,1,5,3,6,4]
    • Output: 5
    • Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.Not 7-1 = 6, as selling price needs to be larger than buying price.
  • 示例2:

    • Input: [7,6,4,3,1]
    • Output: 0
    • Explanation: In this case, no transaction is done, i.e. max profit = 0.
  • 注意点:不要将简单问题想的复杂化。

  • 代码:

#include<iostream>
using namespace std;
#include<vector>

class Solution 
{
public:
	int maxprofit(vector<int> src) 
	{
		int min =	INT_MAX;
		int max = 0;
		for (vector<int>::iterator iter = src.begin(); iter != src.end(); iter++)
		{
			if (*iter < min)
				min = *iter;
			if (max < *iter - min)
				max = *iter - min;
		}
		return max;
	}
};

int main(int argc, char* argv[])
{
	vector<int> src = {7, 1, 5, 3, 6, 4};
	Solution instance = Solution();
	cout << "the max_profit is :" << instance.maxprofit(src) << endl;
	system("pause");
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值