LintCode_150_買賣股票的最佳時機 II

假設有一個數組,它的第i個元素是一個給定的股票在第i天的價格。設計一個算法來找到最大的利潤。你可以完成儘可能多的交易(多次買賣股票)。然而,你不能同時參與多個交易(你必須在再次購買前出售股票)。

樣例

給出一個數組樣例[2,1,2,0,1], 返回 2

開始以爲只是數組中最大的減去最小的,不知道要不要看先後順序,不過既然是按天數,所以應該是要的,而且題目說是多次操作,嘗試了下數據[11,2,1,2,3,1,0,4]輸出的是6,所以應該是按天數遞增然後多次操作後的結果。

這中等題比容易的還容易

class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        // write your code here
        int profits = 0;
        for (int i = 0;i < prices.length-1 ; i++){
            int profit = prices[i+1]-prices[i];
            if(profit > 0){
                profits+=profit;
            }
        }
        return profits;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章