Skip to content

Commit 53f8997

Browse files
committed
Sync LeetCode submission Runtime - 139 ms (19.38%), Memory - 39.1 MB (54.26%)
1 parent 03e99ce commit 53f8997

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
You are given an integer array <code>nums</code>.
2+
<p>A <span data-keyword="subsequence-array">subsequence</span> <code>sub</code> of <code>nums</code> with length <code>x</code> is called <strong>valid</strong> if it satisfies:</p>
3+
4+
<ul>
5+
<li><code>(sub[0] + sub[1]) % 2 == (sub[1] + sub[2]) % 2 == ... == (sub[x - 2] + sub[x - 1]) % 2.</code></li>
6+
</ul>
7+
8+
<p>Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>.</p>
9+
10+
<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>
11+
12+
<p>&nbsp;</p>
13+
<p><strong class="example">Example 1:</strong></p>
14+
15+
<div class="example-block">
16+
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4]</span></p>
17+
18+
<p><strong>Output:</strong> <span class="example-io">4</span></p>
19+
20+
<p><strong>Explanation:</strong></p>
21+
22+
<p>The longest valid subsequence is <code>[1, 2, 3, 4]</code>.</p>
23+
</div>
24+
25+
<p><strong class="example">Example 2:</strong></p>
26+
27+
<div class="example-block">
28+
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,1,1,2,1,2]</span></p>
29+
30+
<p><strong>Output:</strong> 6</p>
31+
32+
<p><strong>Explanation:</strong></p>
33+
34+
<p>The longest valid subsequence is <code>[1, 2, 1, 2, 1, 2]</code>.</p>
35+
</div>
36+
37+
<p><strong class="example">Example 3:</strong></p>
38+
39+
<div class="example-block">
40+
<p><strong>Input:</strong> <span class="example-io">nums = [1,3]</span></p>
41+
42+
<p><strong>Output:</strong> <span class="example-io">2</span></p>
43+
44+
<p><strong>Explanation:</strong></p>
45+
46+
<p>The longest valid subsequence is <code>[1, 3]</code>.</p>
47+
</div>
48+
49+
<p>&nbsp;</p>
50+
<p><strong>Constraints:</strong></p>
51+
52+
<ul>
53+
<li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li>
54+
<li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li>
55+
</ul>
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Approach: Parity of Enumeration Elements
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def maximumLength(self, nums: List[int]) -> int:
8+
res = 0
9+
for pattern in [(0, 0), (0, 1), (1, 0), (1, 1)]:
10+
cnt = 0
11+
for num in nums:
12+
if num % 2 == pattern[cnt % 2]:
13+
cnt += 1
14+
res = max(res, cnt)
15+
16+
return res
17+

0 commit comments

Comments
 (0)