122. 买卖股票的最佳时机 II

给定一个数组 prices ,其中 prices[i] 是一支给定股票第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

brute force

暴力搜索,没什么好说的

当前位置 \(i\) ,搜索其后所有的可能答案,取最大的

def brute_force(arr, start):
  if start >= len(arr):
    return 0
  max_profit = 0
  for i in range(start, len(arr)):
    tmp_max_profit = 0
    for j in range(start+1, len(arr)):
      if arr[j] > arr[i]:
        profit = brute_force(arr, j+1) + arr[j] - arr[i]
        if profit > tmp_max_profit:
          tmp_max_profit = profit
    if tmp_max_profit>max_profit:
      max_profit = tmp_max_profit
  return max_profit

时间复杂度\(O(n^n)\) , 空间复杂度\(O(n)\)


Peak Valley Approach

给定的price数组为\([7, 1, 5, 3, 6, 4]\). 绘制图片有(来自leetcode

显然有,最终的收益来自于所有的峰值减去谷值之和

\(Total\_Profit = \sum_i(height(peak_i)-height(valley_i))\)

def Peak_Valley(prices):
  valley = prices[0]
  peak  = prices[0]
  idx = 0
  max_profit = 0
  while idx < len(prices)-1:
    while idx < len(prices)-1 and prices[idx+1] <= prices[idx]:
      idx+=1
    vally = prices[idx]
    while idx < len(prices)-1 and prices[idx+1] > prices[idx]:
      idx+=1
    peak = prices[idx]
    max_profit += peak-vally
  return max_profit

时间复杂度\(O(n)\), 空间复杂度\(O(1)\)


Simple One Pass

跟上面略微不同的是,只要斜率是正的,就一直买入卖出就可以获得最大利润

Profit Graph

def One_Pass(prices):
  max_profit = 0
  for idx, price in enumerate(prices):
    if idx > 0 and price > prices[idx-1]:
      max_profit += price-prices[idx-1]
  return max_profit
        

时间复杂度\(O(n)\), 空间复杂度\(O(1)\)

posted @ 2021-07-14 23:09  青铜时代的猪  阅读(43)  评论(0)    收藏  举报