Python程式:查詢最長嚴格遞增然後遞減的子列表長度


假設我們有一個名為 nums 的數字列表。我們需要找到最長的子列表的長度,其值嚴格遞增然後遞減(最小長度為3)。

例如,如果輸入為 nums = [7, 1, 3, 5, 2, 0],則輸出為 5,因為子列表 [2, 4, 6, 3, 1] 是嚴格遞增然後遞減的。

為了解決這個問題,我們將遵循以下步驟:

  • i := 0,n := a 的大小,res := -infinity
  • 當 i < n - 2 時,執行
    • st := i
    • linc := 0,ldec := 0
    • 當 i < n - 1 且 a[i] < a[i + 1] 時,執行
      • linc := linc + 1
      • i := i + 1
    • 當 i < n - 1 且 a[i] > a[i + 1] 時,執行
      • ldec := ldec + 1
      • i := i + 1
    • 如果 linc > 0 且 ldec > 0,則
      • res := res 和 (i - st + 1) 中的最大值
    • 當 i < n - 1 且 a[i] 等於 a[i + 1] 時,執行
      • i := i + 1
  • 如果 res >= 0 則返回 res,否則返回 0

讓我們看下面的實現,以便更好地理解:

示例

即時演示

class Solution:
   def solve(self, a):
      i, n, res = 0, len(a), float("-inf")
      while i < n - 2:
         st = i
         linc, ldec = 0, 0
         while i < n - 1 and a[i] < a[i + 1]:
            linc += 1
            i += 1
         while i < n - 1 and a[i] > a[i + 1]:
            ldec += 1
            i += 1
         if linc > 0 and ldec > 0:
            res = max(res, i - st + 1)
         while i < n - 1 and a[i] == a[i + 1]:
            i += 1
      return res if res >= 0 else 0
ob = Solution()
nums = [8, 2, 4, 6, 3, 1]
print(ob.solve(nums))

輸入

[[8, 2, 4, 6, 3, 1]

輸出

5

更新於: 2020年11月19日

385 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.