1. 程式人生 > >leetcode 122 best time to buy and sell tickets

leetcode 122 best time to buy and sell tickets

題目描述如下,大意是可進行多筆交易,但必須先買入在賣出。如不得先買入兩筆在找時間出售兩筆

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.

將如下陣列繪成圖,發現最大利潤是各個谷底-谷峰的差值(2-3,4-5,6-7)
4 1 45 3 66 54 99

若將陣列改造成下種形式,結果也是相同的4 1 (22 33 44)45 3 (10 20 30 40 50 60 )66 54 99

故有兩種解決方案:

1. 尋找整個陣列中的谷底谷峰對

2. 谷底到谷峰的結果就是從谷底一步步加到谷峰的結果。因此不必刻意尋找谷底谷峰,將增加的過程記錄下來,結果也是對的

1對應的程式碼如下:

public int maxProfit(int[] prices) {
        int maxprofit =0;
        int i= 0;
        int vally= 0, peak= 0;
        while(i< prices.length-1){
            while(i< prices.length-1 && prices[i]>=prices[i+1]) i++;
            vally= prices[i];
            while(i< prices.length-1 && prices[i]<prices[i+1])  i++;
            peak= prices[i];
            maxprofit+= peak- vally;//此處如果想實現儲存交易天數還可通過新增hashmap對儲存


        }
        return maxprofit;
    }

2對應的程式碼如下:

public int maxProfit(int[] prices) {
        int maxprofit =0;
        int i= 0;
        while(i< prices.length-1){
            if(prices[i]<prices[i+1]){
                maxprofit+= prices[i+1]- prices[i];
            }
            i++;
        }
        return maxprofit;
        
    }

還寫了一個方法2對應的存買賣天數的方法,略繁瑣,希望有大神可以指導改進-^-

public static int[] maxProfit(int[] prices) {
        int maxprofit = 0;
        int i = 0;
        int[] res= new int[prices.length];
        int index= 0;
        boolean flag= false;
        while (i < prices.length - 1) {
            if (prices[i] < prices[i + 1]) {
                if(!flag)    {flag= true;res[index++]= i;}
                maxprofit += prices[i + 1] - prices[i];
            }
            if(flag== true && prices[i]>= prices[i+1]) {
                flag= false;res[index++]= i;
            }
            if(flag== true && i==prices.length-2) {res[index++]= i+1;}
            i++;
        }
        return res;
    }