Subsequence Sum After Capping Elements Problem
Description
LeetCode Problem 3685.
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 <= 40001 <= nums[i] <= n1 <= k <= 4000
Solution
Approach: Knapsack With Sorted Elements
Sort nums. For a cap x, the elements smaller than x stay as they are, and the c elements that are at least x all become x. A subsequence sum of exactly k then uses some subset of the small elements plus t copies of x, with 0 <= t <= c.
Process x = 1, 2, ..., n. Keep a 0/1 knapsack table reach[s] that says whether the sum s <= k can be made from the elements smaller than x; when x grows, add the newly uncapped elements to the table one at a time. Then answer[x - 1] is true if for some t from 0 to min(c, k / x) we have reach[k - t * x].
Each element is added to the table once, which costs O(k). For a given x at most k / x + 1 values of t are checked, which adds up to a smaller term over all x.
Complexity: O(n * k) time and O(k) extra space.
class Solution:
def subsequenceSumAfterCapping(self, nums: List[int], k: int) -> List[bool]:
n = len(nums)
nums = sorted(nums)
mask = (1 << (k + 1)) - 1
reach = 1 # bit s is set when sum s can be made from the elements below x
i = 0
ans = []
for x in range(1, n + 1):
while i < n and nums[i] < x: # these elements are not changed by the cap
reach = (reach | (reach << nums[i])) & mask
i += 1
c = n - i # the remaining c elements all become x
ok = False
for t in range(min(c, k // x) + 1):
if (reach >> (k - t * x)) & 1:
ok = True
break
ans.append(ok)
return ans