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

思路:

1.采用动态规划的思想 2.从头开始遍历,依次判断后一个数与前一个数的大小,如果比前一个数大,相减,将该值进行存储,针对的是整个列表,这里的最大利润用maxP1来表示 3.然后进行列表的截取操作,讲后续的子列表重复上面的操作,然后判断值的大小, 用动态规划,采用递归思想,比较子列表中相加起来最大的利润,用maxP2表示 4.选取max(maxP1, maxP2)

最初代码:

有错误 ~~~ class Solution(object): def maxProfit(self, prices): “”” :type prices: List[int] :rtype: int “”” if len(prices) == 0: return 0 #在整个列表中找 maxP1 = 0 minC = prices[0]

    # maxP2 = 0
    # minC2 = prices[0]

    for i in range(1, len(prices)):
        if prices[i] < minC:
            minC = prices[i]
        elif prices[i] - minC > maxP1:
            maxP1 = prices[i] - minC
            maxP1 = maxP1+self.maxProfit((prices[i+1:len(prices)]))

    # for j in range(1, len(prices)):
    #     if prices[j] < minC2:
    #         minC2 = prices[j]
    #     elif prices[j] - minC2 > maxP2:
    #         maxP2 = prices[j] - minC2
    #     maxP2 = maxP2 + self.maxProfit(prices[j + 1:len(prices) - 1])
    #         #print(prices[j+1:len(prices) - 1])
    return maxP1

if name == “main”: pic = [2,1,4,5,2,9,7] res = Solution().maxProfit(pic) print(res)


**修改后的代码:**

class Solution(object): def maxProfit(self, prices): “”” :type prices: List[int] :rtype: int “”” if len(prices) == 0: return 0 maxP1 = 0 for i in range(1, len(prices)): if prices[i] > prices[i-1]: maxP1 += prices[i] - prices[i-1] return maxP1

if name == “main”: pic = [2,1,4,5,2,9,7] res = Solution().maxProfit(pic) print(res) ~~~

网上思路: https://blog.csdn.net/coder_orz/article/details/52072136

贪心法,动态规划法

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦