当前位置:   article > 正文

算法题day49(6.4打卡:dp08)

算法题day49(6.4打卡:dp08)

一、leetcode刷题:

1.leetcode题目 121.买卖股票的最佳时机 . - 力扣(LeetCode)(easy)

解决:

  1. class Solution:
  2. def maxProfit(self, prices: List[int]) -> int:
  3. cur_min = prices[0]
  4. maxx = 0
  5. for i in range(1,len(prices)):
  6. maxx = max(maxx,prices[i]-cur_min)
  7. cur_min = min(cur_min,prices[i])
  8. return maxx

2.leetcode题目 122.买卖股票的最佳时机II . - 力扣(LeetCode)(medium)

解决:

贪心算法:

  1. class Solution:
  2. def maxProfit(self, prices: List[int]) -> int:
  3. summ = 0
  4. cur_min = prices[0]
  5. for i in range(1,len(prices)):
  6. cur_min = min(cur_min,prices[i])
  7. if prices[i] > cur_min:
  8. summ += prices[i] - cur_min
  9. cur_min = prices[i]
  10. return summ

动态规划:

  1. class Solution:
  2. def maxProfit(self, prices: List[int]) -> int:
  3. dpf = [0]*len(prices) ##当天无持仓时的最大资产
  4. dpg = [0]*len(prices) ##当天持仓时的最大资产
  5. dpg[0] = -prices[0]
  6. for i in range(1,len(prices)):
  7. dpf[i] = max(dpf[i-1],dpg[i-1] + prices[i])
  8. dpg[i] = max(dpg[i-1],dpf[i-1] - prices[i])
  9. return dpf[len(prices)-1]

3.leetcdoe题目 123.买卖股票的最佳时机III (medium):

动态规划:

  1. class Solution:
  2. def maxProfit(self, prices: List[int]) -> int:
  3. n = len(prices)
  4. buy1 = -prices[0]
  5. buy2 = -prices[0]
  6. sell1=0
  7. sell2 = 0
  8. for p in prices:
  9. buy1 = max(buy1,-p)
  10. sell1 = max(sell1,buy1 + p)
  11. buy2 = max(buy2,sell1-p)
  12. sell2 = max(sell2,buy2+p)
  13. return sell2

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/755700
推荐阅读
相关标签
  

闽ICP备14008679号