LeetCode-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.
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).
給定一個數組,第i個元素代表第i天的價格。設計算法獲取最大的利潤。可以進行多次交易,但是在再次買股票前必須賣掉之前的股票。

算法分析

方法一:

如圖一所示,找出一個相鄰的波峰和波谷,求波峰波谷的差值即為利潤,將所有的利潤相加即可。


圖一:最大利潤
Java代碼
public class Solution {
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        int i = 0;
        //int valley = prices[0];
        //int peak = prices[1];
        while (i < prices.length - 1) {
            while (i < prices.length - 1 && prices[i] >= prices[i + 1])//找出波谷
                i ++;
            int valley = prices[i];
            while (i < prices.length - 1 && prices[i] <= prices[i + 1])//找出波峰
                i ++;
            int peak = prices[i];
            
            maxProfit += peak - valley;
        }
        return maxProfit;
    }
}
方法二:

如圖一圖二所示:


圖二:最大利潤

不管是哪種情況,只要今天的價格比昨天高,就獲得這部分利潤,最后將所有的利潤相加,一定是最大利潤。

Java代碼
public class Solution {
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        for (int i = 1; i < prices.length; i ++) {
            if (prices[i] > prices[i - 1])//如果今天比昨天的值大,就計算一次
                maxProfit += (prices[i] - prices[i - 1]);
        }
        return maxProfit;
    }
}

參考

LeetCode

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容