LeetCode #3685 — MEDIUM

Subsequence Sum After Capping Elements

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given an integer array nums of size n and a positive integer k.

An array capped by value x is obtained by replacing every element nums[i] with min(nums[i], x).

For each integer x from 1 to n, determine whether it is possible to choose a subsequence from the array capped by x such that the sum of the chosen elements is exactly k.

Return a 0-indexed boolean array answer of size n, where answer[i] is true if it is possible when using x = i + 1, and false otherwise.

Example 1:

Input: nums = [4,3,2,4], k = 5

Output: [false,false,true,true]

Explanation:

  • For x = 1, the capped array is [1, 1, 1, 1]. Possible sums are 1, 2, 3, 4, so it is impossible to form a sum of 5.
  • For x = 2, the capped array is [2, 2, 2, 2]. Possible sums are 2, 4, 6, 8, so it is impossible to form a sum of 5.
  • For x = 3, the capped array is [3, 3, 2, 3]. A subsequence [2, 3] sums to 5, so it is possible.
  • For x = 4, the capped array is [4, 3, 2, 4]. A subsequence [3, 2] sums to 5, so it is possible.

Example 2:

Input: nums = [1,2,3,4,5], k = 3

Output: [true,true,true,true,true]

Explanation:

For every value of x, it is always possible to select a subsequence from the capped array that sums exactly to 3.

Constraints:

  • 1 <= n == nums.length <= 4000
  • 1 <= nums[i] <= n
  • 1 <= k <= 4000
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given an integer array nums of size n and a positive integer k. An array capped by value x is obtained by replacing every element nums[i] with min(nums[i], x). For each integer x from 1 to n, determine whether it is possible to choose a subsequence from the array capped by x such that the sum of the chosen elements is exactly k. Return a 0-indexed boolean array answer of size n, where answer[i] is true if it is possible when using x = i + 1, and false otherwise.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Two Pointers · Dynamic Programming

Example 1

[4,3,2,4]
5

Example 2

[1,2,3,4,5]
3
Step 02

Core Insight

What unlocks the optimal approach

  • Sort the array <code>nums</code> in descending order.
  • Build a knapsack DP table <code>dp[idx][sum]</code> where <code>dp[idx][sum] == true</code> if and only if there exists a subsequence of <code>nums[idx]</code> through the end that sums exactly to <code>sum</code>.
  • Observe that capping all values above <code>x</code> to <code>x</code> in a sorted array is equivalent to taking the first <code>t</code> elements (those originally > <code>x</code>) and treating each as <code>x</code>. Precompute which multiples of <code>x</code> up to <code>t * x</code> are selectable.
  • For each cap value <code>x</code> from 1 to <code>n</code>, let <code>t</code> be the number of elements in nums originally greater than <code>x</code>. Then iterate over all sums <code>s</code> with <code>dp[t][s] == true</code> and all counts <code>m</code> from 0 to <code>t</code>; if there exists an <code>m</code> such that <code>s + m * x == k</code>, set <code>answer[x-1]</code> to true. Otherwise, it remains false.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3685: Subsequence Sum After Capping Elements
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3685: Subsequence Sum After Capping Elements
// package main
// 
// import (
// 	"math/big"
// 	"slices"
// )
// 
// // https://space.bilibili.com/206214
// func subsequenceSumAfterCapping1(nums []int, k int) []bool {
// 	slices.Sort(nums)
// 
// 	n := len(nums)
// 	ans := make([]bool, n)
// 	f := make([]bool, k+1)
// 	f[0] = true // 不选元素,和为 0
// 
// 	i := 0
// 	for x := 1; x <= n; x++ {
// 		// 增量地考虑所有等于 x 的数
// 		// 小于 x 的数在之前的循环中已计算完毕,无需重复计算
// 		for i < n && nums[i] == x {
// 			for j := k; j >= nums[i]; j-- {
// 				f[j] = f[j] || f[j-nums[i]] // 0-1 背包:不选 or 选
// 			}
// 			i++
// 		}
// 
// 		// 枚举(从大于 x 的数中)选了 j 个 x
// 		for j := range min(n-i, k/x) + 1 {
// 			if f[k-j*x] {
// 				ans[x-1] = true
// 				break
// 			}
// 		}
// 	}
// 	return ans
// }
// 
// func subsequenceSumAfterCapping(nums []int, k int) []bool {
// 	slices.Sort(nums)
// 
// 	n := len(nums)
// 	ans := make([]bool, n)
// 	f := big.NewInt(1)
// 	u := new(big.Int).Lsh(big.NewInt(1), uint(k+1))
// 	u.Sub(u, big.NewInt(1))
// 
// 	i := 0
// 	for x := 1; x <= n; x++ {
// 		// 增量地考虑所有等于 x 的数
// 		for i < n && nums[i] == x {
// 			shifted := new(big.Int).Lsh(f, uint(nums[i]))
// 			f.Or(f, shifted).And(f, u) // And(f, u) 保证 f 的二进制长度 <= k+1
// 			i++
// 		}
// 
// 		// 枚举(从大于 x 的数中)选了 j 个 x
// 		for j := range min(n-i, k/x) + 1 {
// 			if f.Bit(k-j*x) > 0 {
// 				ans[x-1] = true
// 				break
// 			}
// 		}
// 	}
// 	return ans
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n)
Space
O(1)

Approach Breakdown

BRUTE FORCE
O(n²) time
O(1) space

Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.

TWO POINTERS
O(n) time
O(1) space

Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.

Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

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.

Moving both pointers on every comparison

Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.

Usually fails on: A valid pair can be skipped when only one side should move.

Fix: Move exactly one pointer per decision branch based on invariant.

State misses one required dimension

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.