【LeetCode】121. Best Time to Buy and Sell Stock && 122. Best Time to Buy and Sell Stock II

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天的股市价格减去[0,i-1]天内的最小股市价格,当第i天的股市价格比漆面最低股市价格还低,则更新最低股市价格。然后取最大的股市收益,为DP问题。用profit[i]表示第i天的收益,则minBuyPrice = min(minBuyPrice, prices[i]),并且profit[i] = prices[i]-minBuyPrice. 然后取profit中的最大值。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len = prices.size();
        if(len ==0) return 0;
        if(len == 1) return 0;
        int currMin = prices[0];
        int profit = 0;
        for(int i=1; i < len; i++)
        {
            currMin = min(currMin, prices[i]);
            profit = max(profit, prices[i] - currMin);
        }
        return profit;
    }
};

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

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

贪心法。从前向后遍历数组,只要当天的价格高于前一天的价格,就算入收益。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
       int len = prices.size();
       if(len <=1) return 0;
       int profit = 0;
       for(int i =1; i < prices.size(); i++)
       {
           if(prices[i] > prices[i-1])
            profit+= (prices[i] - prices[i-1]);
       }
       return profit;
    }
};



你可能感兴趣的:(【LeetCode】121. Best Time to Buy and Sell Stock && 122. Best Time to Buy and Sell Stock II)