1. 程式人生 > >[LeetCode] 122. Best Time to Buy and Sell Stock II 買賣股票的最佳時間 II

[LeetCode] 122. Best Time to Buy and Sell Stock II 買賣股票的最佳時間 II

complete design fit sha 一個 tran 利潤 多個 mes

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

給定一個元素代表某股票每天價格的數組,可以買賣股票多次,但不能同時有多個交易,買之前要賣出,求最大利潤。

如果當前價格比之前價格高,則可前一天買入,今天賣出,把差值累計到利潤中,若明日價更高的話,還可以今日買入,明日再拋出。以此類推,遍歷完整個數組後即可求得最大利潤。

Java:

public class Solution {
    public int maxProfit(int[] prices) {
        int res = 0;
        for (int i = 0; i < prices.length - 1; ++i) {
            if (prices[i] < prices[i + 1]) {
                res += prices[i + 1] - prices[i];
            }
        }
        return res;
    }
}

Python:

class Solution:
    def maxProfit(self, prices):
        profit = 0
        for i in xrange(len(prices) - 1):
            profit += max(0, prices[i + 1] - prices[i])     
        return profit

C++:

public class Solution {
    public int maxProfit(int[] prices) {
        int res = 0;
        for (int i = 0; i < prices.length - 1; ++i) {
            if (prices[i] < prices[i + 1]) {
                res += prices[i + 1] - prices[i];
            }
        }
        return res;
    }
}

類似題目:

[LeetCode] 121. Best Time to Buy and Sell Stock 買賣股票的最佳時間

[LeetCode] 123. Best Time to Buy and Sell Stock III 買賣股票的最佳時間 III

[LeetCode] 188. Best Time to Buy and Sell Stock IV 買賣股票的最佳時間 IV

[LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown 買賣股票的最佳時間有冷卻期

  

  

[LeetCode] 122. Best Time to Buy and Sell Stock II 買賣股票的最佳時間 II