LeetCode OJ 之 Best Time to Buy and Sell Stock (买卖股票的最佳时间)

来源:互联网 发布:csol雷神2016数据 编辑:程序博客网 时间:2024/04/20 09:21

题目:

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;    }};




0 0
原创粉丝点击