美文网首页
121. Best Time to Buy and Sell S

121. Best Time to Buy and Sell S

作者: lulupango | 来源:发表于2016-04-28 17:49 被阅读0次

    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 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.

    解题思路:

    给定一个股票的价格序列prices,但是仅能交易一次,求最大利润。也就是找出max(prices[j]-prices[i]),其中j > i。要求只需要遍历一次序列就好了,那么就有两种思路。第一种,每次找到当前最小的价格low,将当前的利润与最大利润做比较,直至得到最大利润;第二种利用动态规划的思想,用d[i]来i表示如果在第i天买出得到的最大利润d[i] = max(d[i - 1] + prices[i] - prices[i - 1],0)。
    现在给出第二种思路的代码:
    

    code:

    int maxProfit(vector<int>& prices)
     {
            vector<int> d(prices.size(), 0);
            int maxp = 0;
            for (int i = 1; i < prices.size(); i++) {
                d[i] = d[i - 1] + prices[i] - prices[i - 1];
                d[i] = max(0,d[i]);
                if (maxp < d[i])
                  maxp = d[i];
            }
            return maxp;
     }
    

    相关文章

      网友评论

          本文标题:121. Best Time to Buy and Sell S

          本文链接:https://www.haomeiwen.com/subject/vnjhrttx.html