πΉ Problem: Maximum Length of a Subsequence With Modular Sum Zero
Difficulty: #Medium
Tags: #DP, #Array, #Greedy, #Math
π Problem Summary
Given an array
nums
and an integerk
, you need to find the length of the longest subsequence where every pair of adjacent elements(a, b)
satisfies:
(a + b) % k == 0
.
π§ My Thought Process
-
Naive Brainstorming (a.k.a "The idea was there... kinda"):
- I figured it had something to do with remainders because of
% k
. - I was thinking in terms of pairing mods somehow β so the core idea managed to show up to class.
- But when it came time to actually write working code? π Hello darkness, my old friend β tabulation DP strikes again.
- I figured it had something to do with remainders because of
-
Why I Couldn't Implement It:
- Because it's tabulation and my brain just refuses to store 2D DP tables in memory like a normal human.
- Every time I try to update a
dp[i][j]
I end up wondering if Iβm accidentally simulating the collapse of spacetime.
-
What Actually Works:
- Create a 2D DP table
dp[prev][curr]
, where each cell stores the max length of a subsequence ending with modulo pair(prev, curr)
. - Update by flipping:
If current number is
num % k
, then for eachprev
in[0, k-1]
,dp[prev][num] = dp[num][prev] + 1
Because(a + b) % k == 0
β¨a % k == (-b) % k
.
- Create a 2D DP table
βοΈ Code Implementation (Python)
from typing import List
class Solution:
def maximumLength(self, nums: List[int], k: int) -> int:
dp = [[0] * k for _ in range(k)] # dp[prev_mod][curr_mod]
res = 0
for num in nums:
num %= k
for prev in range(k):
dp[prev][num] = dp[num][prev] + 1
res = max(res, dp[prev][num])
return res
π₯ This solution works because it leverages the modular symmetry. You basically abuse the 2D array to remember the last good match, and mutate it like a boss.
β±οΈ Time & Space Complexity
Time:
O(n * k)
We iterate over alln
elements and try pairing each withk
mod classes.Space:
O(k^2)
The 2D DP table holds best subsequence lengths for each modulo pair.
π§© Key Takeaways
- β Even if your tabulation brain is weak, recognizing a problem as modular + pair-based is already half the battle.
- π§ When
% k
is involved, think in terms of remainders, not actual numbers. - π Don't be ashamed of struggling with DP tables. Theyβre evil, and youβre brave for trying.
π Reflection (Self-Check)
- [ ] Could I implement this myself without crying?
- [x] Did I at least think in the right direction?
- [x] Do I now understand the logic?
- [x] Will I revisit this later with a new appreciation for
dp[i][j]
?
π Related Problems
- [[300 Longest Increasing Subsequence]]
- [[2915 Length of the Longest Subsequence That Sums to Target]]
π Progress Tracker
Metric | Value |
---|---|
Day | 46 |
Total Problems Solved | 387 |
Confidence Today | π (DP strikes again...) |
Leetcode Rating | 1572 |
Top comments (0)