鱼C论坛

 找回密码
 立即注册
查看: 2028|回复: 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.

  1. class Solution:
  2.     def maxProfit(self, k: int, prices: List[int]) -> int:
  3.         #hold, sold
  4.         if k <= 0 or prices == None or len(prices) == 0:
  5.             return 0
  6.         
  7.         #the maximum trahsanction time is less than k
  8.         if 2 * k > len(prices):
  9.             res = 0
  10.             for i in range(1, len(prices)):
  11.                 res += max(0, prices[i] - prices[i - 1])
  12.             return res
  13.         
  14.         #regular case
  15.         dp = [[-math.inf, 0] for _ in range(k)]
  16.         
  17.         for price in prices:
  18.             temp = dp
  19.             for i in range(k):
  20.                 if i == 0:
  21.                     dp[i][0] = max(temp[i][0], 0 - price)
  22.                     dp[i][1] = max(temp[i][1], temp[i][0] + price)

  23.                 else:
  24.                     dp[i][0] = max(temp[i][0], temp[i - 1][1] - price)
  25.                     dp[i][1] = max(temp[i][1], temp[i][0] + price)
  26.                     
  27.         return dp[-1][-1]
复制代码

本帖被以下淘专辑推荐:

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-4 10:44

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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