Best Time to Buy and Sell Stock

本文介绍了一种用于计算股票买卖最大利润的算法。通过维护一个当前最低价格和最大利润变量,该算法能在O(n)的时间复杂度内找到最佳买卖时机,从而获得最大利润。

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

题目:

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.

思想:

1. 因为只可以交易一次,所以可以看成求数组的最大差(注意:先买后卖,所以只可能是后面的数减去前面的数);

2. 为了程序不超时,先求出极值(局部最大和最小值),放在vector中

代码:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
    	vector<int> result;
    	int j = 0;
    	int max_dis = 0;
    	int n = prices.size();
    	while(j < n) {
    		while(j+1 < n && prices[j] >= prices[j+1])
    			j++;
    		if(j < n-1) {
    			result.push_back(prices[j]);
    			j++;
    			while(j+1 < n && prices[j] <= prices[j+1])
    				j++;
    			result.push_back(prices[j]);
    		}
    		j++;
    	}
    	int sz = result.size();
    	for(int i = 0; i < sz-1; i += 2) {
    		for(int j = i+1; j < sz; j += 2) {
    			int tmp = result[j] - result[i];
    			if(tmp > max_dis)
    				max_dis = tmp;
    		} 
		} 
		return max_dis;
	}
};

上面第一次实现的比较复杂。

参考http://blog.youkuaiyun.com/pickless/article/details/12033745

使用cur_min表示之前股票的最低价,max_profit表示当前的股票最大利益

class Solution {
public:
    int maxProfit(vector<int> &prices) {
    	if(prices.size() == 0)
    		return 0;
    	int max_profit = 0, cur_min = prices[0];
    	for(int i = 1; i < prices.size(); i++) {
    		int tmp = prices[i] - cur_min;
    		if(tmp > max_profit)
    			max_profit = tmp;
    		if(prices[i] < cur_min)
    			cur_min = prices[i];	
    	}
    	return max_profit;
	}
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值