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

  1. 暴力法

    计算所有可能的交易组合相对应的利润,并找出它们其中的最大利润。

    • Python3

      class Solution:
          def maxProfit(self, prices: List[int]) -> int:
              return self.calculate(prices, 0)
      
          def calculate(self, prices, s):
              if s >= len(prices):
                  return 0
      
              max = 0
              for start in range(s, len(prices)):
                  max_profit = 0
                  for i in range(start+1, len(prices)):
                      if prices[start] < prices[i]:
                          profit = self.calculate(prices, i+1) + prices[i] - prices[start]
                          if profit > max_profit:
                              max_profit = profit
                  if max_profit > max:
                      max = max_profit
              return max
      
    • Go

      func maxProfit(prices []int) int {
          return cal(prices, 0)
      }
      
      func cal(prices []int, s int) int {
          if s > len(prices) {
              return 0
          }
          max := 0
          for i := s; i < len(prices); i++ {
              maxprices := 0
              for j := i+1; j < len(prices); j++ {
                  if prices[i] < prices[j]{
                      pro := (prices[j] - prices[i]) + cal(prices, j+1)
                      if pro > maxprices {
                          maxprices = pro
                      }
                  }
      
              }
              if max < maxprices {
                  max = maxprices
              }
          }
          return max
      }
      
  2. 贪心法

    • 从第 i 天(这里 i >= 1)开始,与第 i - 1 的股价进行比较,如果股价有上升(严格上升),就将升高的股价( prices[i] - prices[i- 1] )记入总利润,按照这种算法,得到的结果就是符合题意的最大利润。

    • Python

      class Solution:
          def maxProfit(self, prices: List[int]) -> int:
              max_profit = 0
              for i in range(1, len(prices)):
                  if prices[i] > prices[i-1]:
                      max_profit += prices[i] - prices[i-1]
              return max_profit
      
    • Go

      func maxProfit(prices []int) int {
          max := 0
          for i :=1; i<len(prices); i++{
              if prices[i] > prices[i-1]{
                  max += prices[i] - prices[i-1]
              }
          }
          return max
      }
      
posted @ 2020-06-16 22:42  暮晨  阅读(144)  评论(0编辑  收藏  举报

Aaron Swartz was and will always be a hero