用 Python 编写程序,查找最长严格递增然后递减的子列表的长度
pythonserver side programmingprogramming
假设我们有一个名为 nums 的数字列表。我们必须找到最长子列表的长度,使得(最小长度 3)其值严格递增然后递减。
因此,如果输入为 nums = [7, 1, 3, 5, 2, 0],则输出将为 5,因为子列表为 [2, 4, 6, 3, 1] 严格递增然后递减。
为了解决这个问题,我们将遵循以下步骤 −
- i := 0, n := size of a, res := -infinity
- while 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
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

