[LeetCode]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.

思路: 低买高卖, 找一个低点,再找后面的一个最高点。如  [3,2,6,5,0,3] 就是 2 - 6 复杂度O(n^2)。

里面有两个小优化, 找sell的时候要找到 一个较小的值,

找buy的时候,若以前找到了一个 buy(sell<buy) ,就用以前的,否则寻找max(price[sell...n-1])的最大值下标。、

遇到一个小问题 i + 1 < prices.size() 写成 i < prices.size () -1 当prices为空的时候 会出错,不知道为什么。。。

可能是由于 size()的返回值类型是 vector<int>::size_type 减一之后值为 4294967295.....


class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
  
        int max = 0;
		int  buy = -1;
		int  sell = -1;
        for( int i = 0 ; i + 1 < prices.size() ;i++)
		{
             // find first low prices
			if(i+1 < prices.size() && prices[i]>= prices[i+1])
				continue;
            buy = i ;
            if(sell > buy )
			// buy  is the largest  between prices[s....n-1]  s<i
            {
              int profit = prices[sell] - prices[buy];
              if(profit > max)
                  max = profit;
            }else{
               sell = i+1 ;    
               for(int j = i + 1; j< prices.size();j++)
               {
                   if(prices[j]>prices[sell])
                        sell = j;
               } 
               int profit = prices[sell] - prices[buy];
                if(profit > max)
                  max = profit;
            }
			
		}
		return max;
    }
};

后来想了一下,想到一个大改进;

如果我在 第i天买,那么在 i+1 到 最后一天的最高价 里卖出, 才能赚最多。

 可以做预处理,把这些子数组的最大值求出来。复杂度O(n)


//
class Solution{

public:
		int max1(int &a, int &b)
		{
				return a > b ?a:b;
		}
	 int maxProfit(vector<int> &prices) {
        	// Start typing your C/C++ solution below
      		// DO NOT write int main() function
		int max = 0;
		if(prices.size()<2)
			return 0;
		vector<int> submax(prices);
		for(int j = prices.size()-2; j >= 0 ; j--)
		{
			if(j== prices.size()-2)
				submax[j] = *(prices.end()-1);
			else
				submax[j]=  max1(submax[j+1] , prices[j+1]); 
		}
		for(int i = 0 ; i + 1 < prices.size() ; i++)
		{
			int tmp = submax[i]-prices[i];
			if(tmp>max)
				max = tmp;
		}
	return max;
	}
};


总结,对于stl的 iterator 和 size_type 两个类型不是太熟悉,总是习惯于C的下标操作,总造成一些错误,边看会primer和effective c++



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值