题目

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。
注意你不能在买入股票前卖出股票。
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

方案一(暴力解法)

  1. class Solution:
  2. def maxProfit(self, prices: List[int]) -> int:
  3. # 暴力解法
  4. res = 0
  5. for i in range(len(prices)):
  6. for j in range(i + 1, len(prices)):
  7. res = max(prices[j] - prices[i], res)
  8. return res
  • 超时

    方案二(动态规划)

  1. class Solution:
  2. def maxProfit(self, prices: List[int]) -> int:
  3. if not prices:
  4. return 0
  5. # dp[i] 表示前 i 天能获得的最大利润
  6. dp = [0]
  7. _min = prices[0] # 前 i 天的最小值
  8. for i in range(1, len(prices)):
  9. dp.append(max(dp[i - 1], prices[i] - _min))
  10. if _min > prices[i]:
  11. _min = prices[i]
  12. return max(dp)