#3685

Subsequence Sum After Capping Elements

Medium
ArrayTwo PointersDynamic ProgrammingSortingDynamic ProgrammingKnapsack Problem
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(nk)
Space
O(1)
O(k)
💡

Intuition

Time O(nk)Space O(k)

Sort the array and use a dynamic programming approach to track achievable sums for each capped value efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort nums in descending order.
  2. 2Step 2: Initialize a boolean array dp of size k + 1 to track achievable sums.
  3. 3Step 3: For each x from 1 to n, cap nums and update dp to reflect achievable sums.
solution.py12 lines
1def canSum(nums, k):
2    nums.sort(reverse=True)
3    result = []
4    for x in range(1, len(nums) + 1):
5        dp = [False] * (k + 1)
6        dp[0] = True
7        for num in nums:
8            if num > x: continue
9            for j in range(k, num - 1, -1):
10                dp[j] = dp[j] or dp[j - num]
11        result.append(dp[k])
12    return result

Complexity note: The DP approach iterates through nums and updates achievable sums, leading to O(nk) complexity.

  • 1Capping elements reduces the problem size.
  • 2Dynamic programming efficiently tracks achievable sums.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.