Py3 C++奇偶交錯奇偶子數列解Leecode 3201 Find the Maximum Length of Valid Subsequence I
求最長有效子序列,使得 (sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2,有 3 種可能的情況
-全為偶數
-全為奇數
-或奇偶交錯子序列
[Py3解請進]
-----
To find the longest valid subsequence such that (sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2, it has 3 possible cases
- all evens
- all odds
- or alternative subsequence
class Solution: def maximumLength(self, nums: List[int]) -> int: n=len(nums) if n==2: return 2 z=nums[0]&1 Len=[1-z, z, 1] for xx in nums[1:]: x=xx&1 Len[x&1]+=1 if x!=z: Len[2]+=1 z=1-z return max(Len)
沒有留言:
張貼留言