Leetcode P0122"Best Time to Buy and Sell Stock II" 题解

2020/09/10 Leetcode

博文中会简要介绍Leetcode P0122题目分析及解题思路。

“Best Time to Buy and Sell Stock II”是p0121的变形题,而p0188则是它的原型题。同样地,这道题也是p0188的简化版,不同于其原型题,这道题可以使用贪心算法,因为交易次数不受限制。

Say you have an array prices 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 (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

贪心算法的思路其实很简单,总是在极小值买入,在下一个极大值卖出即可。或者另一种解释是若下一个交易日股价大于当前交易日的股价则在当前交易日买入,再下一个交易日卖出。

以下是Java的题解代码实现。

class Solution {
    public int maxProfit(int[] prices) {
        int days = prices.length, profit = 0, minima = 0, maxima = 0;
        // Pre-prepore
        int[] stocks = new int[days+2];
        stocks[0] = Integer.MAX_VALUE;
        stocks[days+1] = Integer.MIN_VALUE;
        System.arraycopy(prices, 0, stocks, 1, days);
        
        // Greedy
        for (int day=1; day<=days; ++day) {
            if (stocks[day] <= stocks[day-1] && stocks[day] <= stocks[day+1])
                minima = stocks[day];
            else if (stocks[day] >= stocks[day-1] && stocks[day] >= stocks[day+1]) {
                maxima = stocks[day];
                
                profit += (maxima-minima);
                minima = maxima;
            }
        }
        
        return profit;
    }
}

以下是C++的题解代码实现。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int days = prices.size();
        // Pre-prepare
        vector<int> stocks(days+2);
        stocks[0] = INT_MAX;
        copy(prices.cbegin(), prices.cend(), stocks.begin()+1);
        stocks[days+1] = INT_MIN;
        
        // Greedy
        int minima = 0, maxima = 0, profit = 0;
        for (int day=1; day<=days; ++day) {
            if (stocks[day] <= stocks[day-1] && stocks[day] <= stocks[day+1])
                minima = stocks[day];
            else if (stocks[day] >= stocks[day-1] && stocks[day] >= stocks[day+1]) {
                maxima = stocks[day];
                profit += maxima-minima;
                
                minima = maxima;
            }
        }
        
        return profit;
    }
};

Search

    Table of Contents