2760
给你一个下标从 0 开始的整数数组 nums
和一个整数 threshold
。
请你从 nums
的子数组中找出以下标 l
开头、下标 r
结尾 (0 <= l <= r < nums.length)
且满足以下条件的 最长子数组 :
nums[l] % 2 == 0
- 对于范围
[l, r - 1]
内的所有下标i
,nums[i] % 2 != nums[i + 1] % 2
- 对于范围
[l, r]
内的所有下标i
,nums[i] <= threshold
以整数形式返回满足题目要求的最长子数组的长度。
注意:子数组 是数组中的一个连续非空元素序列。
示例 1:
输入:nums = [3,2,5,4], threshold = 5 输出:3 解释:在这个示例中,我们选择从 l = 1 开始、到 r = 3 结束的子数组 => [2,5,4] ,满足上述条件。 因此,答案就是这个子数组的长度 3 。可以证明 3 是满足题目要求的最大长度。
class Solution(object): def longestAlternatingSubarray(self, nums, threshold): """ :type nums: List[int] :type threshold: int :rtype: int """ l = len(nums) ans = 0 count = 0 for j in range(l): count = 0 if nums[j]%2==0 and nums[j]<=threshold: for i in range(j,l): if (i-j)%2==0 and nums[i]%2 == 0 and nums[i]<=threshold: count = count + 1 ans=max(ans,count) elif (i-j)%2!=0 and nums[i]%2 != 0 and nums[i]<=threshold: count = count + 1 ans=max(ans,count) else: break else: continue return ans
Work Hard
But do not forget to enjoy life😀
本文来自博客园,作者:YuhangLiuCE,转载请注明原文链接:https://www.cnblogs.com/YuhangLiuCE/p/17837298.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)