LeetCode OJ 之 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 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。

假设有一个数组,第i个元素是一个第i天的股票的价格。
如果你只被允许完成最多一次交易(即只能买一次和卖一次股票),设计一个算法,找出最大的利润。

核心思想请参看:最大子数组问题

代码1:

class Solution {
public:
    int maxProfit(vector<int> &prices) 
    {
        //思路:求出每相邻两天的收益,连续n个相邻两天收益最大的即可获得最大利润。核心思想是求最大子数组问题
        vector<int> ivec;//存储prices内前后数之差,即相邻两天股票收益
        if(prices.size() == 0)
            return 0;
        ivec.push_back(0);//首天收益为0
        for(vector<int>::iterator iter1 = prices.begin() ; iter1 != prices.end()-1 ; iter1++)
        {
            ivec.push_back(*(iter1 + 1) - *iter1);//把相邻两天的股票收益存入ivec
        }
        //下面是求数组中,子数组中和最大的,实质是求股票的最大收益
        int preSum=0,curSum=0;//pre是之前保存的子数组元素和最大的,cur保存当前子数组和最大的
        for(vector<int>::iterator iter2 = ivec.begin() ; iter2 != ivec.end() ; iter2++)
        {
            curSum += *iter2;
            if(preSum <= curSum)//如果之前保存的最大值比当前的最大值小,则替换掉
                preSum = curSum;
            if(curSum <= 0)//如果当前最大收益<=0,则没有保存的必要了,重新计算后面的
                curSum = 0;
        }
        return preSum;
    }
};

代码2:

class Solution {
public:
    int maxProfit(vector<int> &prices) 
    {
        //思路:分别找到价格最低和最高的一天,低进高出,最低的要在最高前
        if (prices.size() < 2) 
            return 0;
        int profit = 0; //当前最大收益
        int cur_min = prices[0]; // 当前最低股票价
        for (int i = 1; i < prices.size(); i++) 
        {
            cur_min = min(cur_min, prices[i]);//遍历到当前的最低股价
            profit = max(profit, prices[i] - cur_min);//当前价格-最低价得到的收益和之前保存的最大收益指,取较大者
        }
        return profit;
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值