Skip to content

Commit fe251f7

Browse files
committed
Sync LeetCode submission Runtime - 1361 ms (76.23%), Memory - 25.9 MB (23.77%)
1 parent 53f8997 commit fe251f7

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
You are given an integer array <code>nums</code> and a <strong>positive</strong> integer <code>k</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]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k.</code></li>
6+
</ul>
7+
Return the length of the <strong>longest</strong> <strong>valid</strong> subsequence of <code>nums</code>.
8+
<p>&nbsp;</p>
9+
<p><strong class="example">Example 1:</strong></p>
10+
11+
<div class="example-block">
12+
<p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5], k = 2</span></p>
13+
14+
<p><strong>Output:</strong> <span class="example-io">5</span></p>
15+
16+
<p><strong>Explanation:</strong></p>
17+
18+
<p>The longest valid subsequence is <code>[1, 2, 3, 4, 5]</code>.</p>
19+
</div>
20+
21+
<p><strong class="example">Example 2:</strong></p>
22+
23+
<div class="example-block">
24+
<p><strong>Input:</strong> <span class="example-io">nums = [1,4,2,3,1,4], k = 3</span></p>
25+
26+
<p><strong>Output:</strong> <span class="example-io">4</span></p>
27+
28+
<p><strong>Explanation:</strong></p>
29+
30+
<p>The longest valid subsequence is <code>[1, 4, 1, 4]</code>.</p>
31+
</div>
32+
33+
<p>&nbsp;</p>
34+
<p><strong>Constraints:</strong></p>
35+
36+
<ul>
37+
<li><code>2 &lt;= nums.length &lt;= 10<sup>3</sup></code></li>
38+
<li><code>1 &lt;= nums[i] &lt;= 10<sup>7</sup></code></li>
39+
<li><code>1 &lt;= k &lt;= 10<sup>3</sup></code></li>
40+
</ul>
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Approach: Dynamic Programming
2+
3+
# Time: O(k^2 + n * k)
4+
# Space: O(k^2)
5+
6+
class Solution:
7+
def maximumLength(self, nums: List[int], k: int) -> int:
8+
dp = [[0] * k for _ in range(k)] # dp[i][j] represents the length of sequence ending with remainder j where the previous remainder was i
9+
res = 0
10+
11+
for num in nums:
12+
num %= k
13+
for prev in range(k):
14+
dp[prev][num] = dp[num][prev] + 1
15+
res = max(res, dp[prev][num])
16+
return res
17+

0 commit comments

Comments
 (0)