鱼C论坛

 找回密码
 立即注册
查看: 2380|回复: 0

[学习笔记] Leetcode 188. Best Time to Buy and Sell Stock IV

[复制链接]
发表于 2020-9-10 22:32:24 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Seawolf 于 2020-9-10 22:33 编辑

Say you have an array for which the i-th element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Example 1:

Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:

Input: [3,2,6,5,0,3], k = 2
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.
             Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:
        #hold, sold
        if k <= 0 or prices == None or len(prices) == 0:
            return 0
        
        #the maximum trahsanction time is less than k
        if 2 * k > len(prices):
            res = 0
            for i in range(1, len(prices)):
                res += max(0, prices[i] - prices[i - 1])
            return res
        
        #regular case
        dp = [[-math.inf, 0] for _ in range(k)]
        
        for price in prices:
            temp = dp
            for i in range(k):
                if i == 0:
                    dp[i][0] = max(temp[i][0], 0 - price)
                    dp[i][1] = max(temp[i][1], temp[i][0] + price)

                else:
                    dp[i][0] = max(temp[i][0], temp[i - 1][1] - price)
                    dp[i][1] = max(temp[i][1], temp[i][0] + price)
                    
        return dp[-1][-1]

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-11-22 18:05

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表