【LeetCode】122、買賣股票的最佳時機 II


Best Time to Buy and Sell Stock II

題目等級:Easy

題目描述:

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

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

  題意:給定一個數組,它的第 i 個元素是一支給定股票第 i 天的價格。設計一個算法來計算所能獲取的最大利潤。你可以盡可能地完成更多的交易(多次買賣一支股票),必須在再次購買前出售掉之前的股票。


解題思路(貪心策略):

  本題和上一題相比,唯一的區別是:這里對買賣次數沒有限制。

  這里我們可以采用貪心策略來解決:首先我們需要理解一點,第i天買入,第j天賣出得到的收益和第i天買入,第i+p天賣出,第i+p天再買入,第j天賣出得到的收益是相同的。比如[1,2,3,4,5],很明顯我們知道最大收益是4,可以看作是第一天買入,第五天賣出,但是也可以看作是第1天買入,第二天賣出,同時買入,第三天又賣出,同時買入······

  理解了這一點,我們就清楚這里為什么能用貪心的思想了,從第一天開始買入,只要有收益就可以直接賣出,接下來再買入,同樣一旦有收益就可以賣出,這是一種典型的貪心思想,局部最優達到全局最優。

  從代碼角度來說,我們只需要累加后一天和前一天的差(后一天大於前一天的情況下)即可。

	public int maxProfit(int[] prices) {
        //貪心法
        if(prices==null || prices.length==0)
            return 0;
        int profit=0;
        for(int i=1;i<prices.length;i++){
            if(prices[i]>prices[i-1])
                profit+=(prices[i]-prices[i-1]);
        }
        return profit;
    }

  可以看出來,代碼實現很簡潔,時間復雜度:O(n),空間復雜度O(1)。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM