Magicsheet logo

Length of the Longest Subsequence That Sums to Target

Medium
86.8%
Updated 6/1/2025

Length of the Longest Subsequence That Sums to Target

What is this problem about?

The "Length of the Longest Subsequence That Sums to Target interview question" is a variation of the classic subset sum problem. You are given an array of integers and a target value. Your task is to find the maximum possible length of a subsequence whose elements sum up exactly to the target. If no such subsequence exists, you should return -1. This "Length of the Longest Subsequence That Sums to Target coding problem" adds an optimization layer to the standard existence check of subset sum.

Why is this asked in interviews?

This problem is a popular choice for assessing a candidate's mastery of the "Dynamic Programming interview pattern". Companies like Meta and Intuit use it to see if a candidate can adapt a well-known algorithm (Subset Sum) to solve a slightly different objective (maximizing length instead of just finding a boolean answer). it tests your ability to define DP states and transitions effectively.

Algorithmic pattern used

The primary pattern is Dynamic Programming, specifically a variation of the 0/1 Knapsack problem. You create a DP array where dp[i] represents the maximum length of a subsequence that sums to i. Initialize the array with a small value (like -1) and set dp[0] = 0. For each number in the input array, you iterate backwards through the DP array and update: dp[sum] = max(dp[sum], dp[sum - num] + 1).

Example explanation

Array: [1, 2, 3, 4], Target: 5

  1. Initial DP: dp[0]=0, others=-1.
  2. Process 1: dp[1] = max(-1, dp[0]+1) = 1.
  3. Process 2: dp[3] = max(-1, dp[1]+1) = 2, dp[2] = max(-1, dp[0]+1) = 1.
  4. Process 3: dp[5] = max(-1, dp[2]+1) = 2.
  5. Process 4: dp[5] = max(2, dp[1]+1) = 2. (Wait, 1+4=5, length 2. 2+3=5, length 2. The longest is 2). Result: The max length for target 5 is 2.

Common mistakes candidates make

  • Forward iteration: Iterating forwards through the DP array when using a 1D array, which leads to using the same element multiple times (this would solve the "Unbounded" version instead of the "Subsequence" version).
  • Incorrect initialization: Forgetting to set dp[0] = 0 or using 0 as a placeholder for "not reached" when 0 could be a valid length.
  • O(2^n) recursion: Attempting to solve it using simple recursion without memoization, which will fail for larger arrays.

Interview preparation tip

When you see a problem asking for the "longest", "shortest", "maximum", or "minimum" count of elements to reach a sum, it's almost always a DP problem. Practice the 0/1 Knapsack template until it's second nature.

Similar Questions