leetcode-121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on dayi.

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.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

题的大意

给出连续N天的股票价格(买入或者卖出的价格),只能买卖一次的话,最大的差价是多少(少于0则为0)。

思路分析

1. 直接查找:最容易想到的思路是暴力查找方法,即遍历两遍,找出第M个和第M+n个元素的最大差值即可,时间复杂度O(n^2),显然不是最优方法,而且提交时会TLE,超时了,显然改题有时间复杂度要求。

2. 有没有只遍历一次的方法(O(n))呢?观察一下股票买卖和最大差值间的关系,最大差值其实可以分成N(N>=1)个连续差值的和,例如:prices[7, 1, 5, 3, 6, 4]中,最大差值是prices[4] - prices[1] = 6 - 1 = 5,分成连续差价: (prices[4] -prices[3]) + (prices[3] -prices[2]) + (prices[2] -prices[1]) = 4 + (-2) + 3 = 5。

所以该题可以换一种说法: 寻找N个连续差值的和中最大的一个。这个题其实Leetcode中另外一个题:53. Maximum Subarray,只不过我们要求股票买卖不能赔钱(最大子数组如果少于零,返回零)。

要算最大子数组就相对简单一些了,我们知道一个数加上一个小于零的数字会导致结果比加之前小,根据这个性质可以得到最大子数组。代码如下,具体逻辑参考注释

    int maxSubArray(vector<int>& nums) {
        int iSum = 0;
        int iMaxSum = INT_MIN;//最大子数组可能是负的,所以要初始化为最小值
        for(unsigned int i = 0; i < nums.size(); ++i)
        {
            if(iSum <= 0)//上一个子数组小于零,根据上面提到的性质,舍弃它
            {
                iSum = nums[i];
            }
            else//反之,继续向子数组中添加新元素
            {
                iSum += nums[i];   
            }

            if(iSum > iMaxSum)//更新最大子数组
            {
                iMaxSum = iSum;
            }
        }
        return iMaxSum;
    }


再结合下本题,把上述元素替换为连续差价就好了,代码如下
    int maxProfit(vector<int>& prices) {
        int iMax = INT_MIN;
        int iTemp = 0;
        for(unsigned int i = 1; i < prices.size(); ++i)
        {
            int iDiffer = prices[i] - prices[i - 1];//子数组是有差价组成的
            if(iTemp > 0)
            {
                iTemp += iDiffer;
            }
            else
            {
                iTemp = iDiffer;
            }

            if(iTemp > iMax)
            {
                iMax = iTemp;
            }
        }
        return iMax > 0 ? iMax : 0;//不能赔钱
    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值