Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an integer array nums and a non-negative integer k. A sequence of integers seq is called good if there are at most k indices i in the range [0, seq.length - 2] such that seq[i] != seq[i + 1].
Return the maximum possible length of a good subsequence of nums.
Example 1:
Input: nums = [1,2,1,1,3], k = 2
Output: 4
Explanation:
The maximum length subsequence is [1,2,1,1,3].
Example 2:
Input: nums = [1,2,3,4,5,1], k = 0
Output: 2
Explanation:
The maximum length subsequence is [1,2,3,4,5,1].
Constraints:
1 <= nums.length <= 5001 <= nums[i] <= 1090 <= k <= min(nums.length, 25)Problem summary: You are given an integer array nums and a non-negative integer k. A sequence of integers seq is called good if there are at most k indices i in the range [0, seq.length - 2] such that seq[i] != seq[i + 1]. Return the maximum possible length of a good subsequence of nums.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Dynamic Programming
[1,2,1,1,3] 2
[1,2,3,4,5,1] 0
longest-increasing-subsequence)maximum-length-of-repeated-subarray)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3176: Find the Maximum Length of a Good Subsequence I
class Solution {
public int maximumLength(int[] nums, int k) {
int n = nums.length;
int[][] f = new int[n][k + 1];
int ans = 0;
for (int i = 0; i < n; ++i) {
for (int h = 0; h <= k; ++h) {
for (int j = 0; j < i; ++j) {
if (nums[i] == nums[j]) {
f[i][h] = Math.max(f[i][h], f[j][h]);
} else if (h > 0) {
f[i][h] = Math.max(f[i][h], f[j][h - 1]);
}
}
++f[i][h];
}
ans = Math.max(ans, f[i][k]);
}
return ans;
}
}
// Accepted solution for LeetCode #3176: Find the Maximum Length of a Good Subsequence I
func maximumLength(nums []int, k int) (ans int) {
f := make([][]int, len(nums))
for i := range f {
f[i] = make([]int, k+1)
}
for i, x := range nums {
for h := 0; h <= k; h++ {
for j, y := range nums[:i] {
if x == y {
f[i][h] = max(f[i][h], f[j][h])
} else if h > 0 {
f[i][h] = max(f[i][h], f[j][h-1])
}
}
f[i][h]++
}
ans = max(ans, f[i][k])
}
return
}
# Accepted solution for LeetCode #3176: Find the Maximum Length of a Good Subsequence I
class Solution:
def maximumLength(self, nums: List[int], k: int) -> int:
n = len(nums)
f = [[1] * (k + 1) for _ in range(n)]
ans = 0
for i, x in enumerate(nums):
for h in range(k + 1):
for j, y in enumerate(nums[:i]):
if x == y:
f[i][h] = max(f[i][h], f[j][h] + 1)
elif h:
f[i][h] = max(f[i][h], f[j][h - 1] + 1)
ans = max(ans, f[i][k])
return ans
// Accepted solution for LeetCode #3176: Find the Maximum Length of a Good Subsequence I
/**
* [3176] Find the Maximum Length of a Good Subsequence I
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn maximum_length(nums: Vec<i32>, k: i32) -> i32 {
use std::collections::HashMap;
let k = k as usize;
let mut map = HashMap::with_capacity(nums.len());
let mut mx = vec![0; k + 2];
for x in nums {
let entry = map.entry(x).or_insert(vec![0; k + 1]);
for j in (0..=k).rev() {
entry[j] = entry[j].max(mx[j]) + 1;
mx[j + 1] = mx[j + 1].max(entry[j]);
}
}
mx[k + 1]
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_3176() {
assert_eq!(4, Solution::maximum_length(vec![1, 2, 1, 1, 3], 2));
assert_eq!(2, Solution::maximum_length(vec![1, 2, 3, 4, 5, 1], 0));
}
}
// Accepted solution for LeetCode #3176: Find the Maximum Length of a Good Subsequence I
function maximumLength(nums: number[], k: number): number {
const n = nums.length;
const f: number[][] = Array.from({ length: n }, () => Array(k + 1).fill(0));
let ans = 0;
for (let i = 0; i < n; ++i) {
for (let h = 0; h <= k; ++h) {
for (let j = 0; j < i; ++j) {
if (nums[i] === nums[j]) {
f[i][h] = Math.max(f[i][h], f[j][h]);
} else if (h) {
f[i][h] = Math.max(f[i][h], f[j][h - 1]);
}
}
++f[i][h];
}
ans = Math.max(ans, f[i][k]);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.