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 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& prices)
 {
        vector 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 Stock)