思路:
1.确定数组下标及其含义店的dp[i]即为判断奇偶数的最大数目。
2.找到递推公式,可以分步思考,找出一定范围内不同的值
3.初始化数组,将初始元素全变位为零
4.确定遍历范围,使用循环将数组遍历,根据上述条件写成判断条件,根据不同条件执行不同命令。
5.返回最长奇偶数组。
class Solution:
def longestArray(self, nums: list[int], threshold: int) -> int:
# 初始化最长连续偶数长度为0,当前连续偶数长度为0
res, dp = 0, 0
# 从列表末尾向前遍历
for l in range(len(nums) - 1, -1, -1):
# 如果当前数字大于阈值,重置当前连续偶数长度为0
if nums[l] > threshold:
dp = 0
# 如果当前数字是偶数且与前一个数字的奇偶性不同,当前连续偶数长度加1
elif l == len(nums) - 1 or nums[l] % 2 != nums[l + 1] % 2:
dp = dp + 1
# 如果当前数字是奇数或者与前一个数字的奇偶性相同,重置当前连续偶数长度为1
else:
dp = 1
# 如果当前数字是偶数且当前连续偶数长度大于最长连续偶数长度,更新最长连续偶数长度
res = dp if nums[l] % 2 == 0 and dp > res else res
# 返回最长连续偶数长度
return res
# 测试
r = Solution()
print(r.longestArray([2, 4, 6, 8, 10], 5)) # Output: 5