用 Python 编写程序,从数字列表中查找最长符号交替子序列的长度
pythonserver side programmingprogramming
假设我们有一个名为 nums 的数字列表,我们必须找到对每个连续数字翻转符号的最长子序列的长度。
因此,如果输入为 nums = [1, 3, -6, 4, -3],则输出将为 4,因为我们可以选择 [1, -6, 4, -3]。
为了解决这个问题,我们将遵循以下步骤 −
- pos := 0, neg := 0
- 对于 nums 中的每个 n,执行
- 如果 n < 0,则
- neg := pos + 1
- 否则,
- pos := neg + 1
- 如果 n < 0,则
- 返回 pos 和 neg 中的最大值
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, nums): pos = neg = 0 for n in nums: if n < 0: neg = pos + 1 else: pos = neg + 1 return max(pos, neg) ob = Solution() nums = [1, 3, -6, 4, -3] print(ob.solve(nums))
输入
[1, 3, -6, 4, -3]
输出
4
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

