Subset Count Under Sum Constraint and Divisor Index
Math & Bit ManipulationAuto-graded · 23 test casesLast updated
Find the maximum number of elements from an array whose sum is at most a given target n, and compute the k-th smallest positive divisor of a number N.
You are given an integer array arr, a sum bound n, and two positive integers N and K. Return a list of two integers [max_count, kth_divisor]:
-
max_count: The maximum number of elements you can select fromarrsuch that the sum of the selected elements is less than or equal ton.- You can choose any subset of indices from
arr(including the empty subset, which has sum0and count0, or the full set of elements). - If the sum of all negative numbers in
arris already greater thann(i.e. $\sum_{x < 0} x > n$), you cannot even take all negative elements. In that case, the maximum number of elements whose sum is $\le n$ is still achievable by taking all negative numbers plus all zeros, provided their total sum $\le n$. More precisely, an optimal selection strategy always includes all negative elements and all zeros, then greedily adds strictly positive elements in ascending order as long as the total sum remains $\le n$. If taking all negative elements (and all zeros) results in a total sum $> n$, return0.
- You can choose any subset of indices from
-
kth_divisor: The $K$-th smallest positive integer divisor ofN(1-indexed). IfNhas fewer thanKpositive integer divisors, return-1.
Constraints
- $1 \le |arr| \le 200,000$
- $-10^9 \le arr[i] \le 10^9$
- $-10^{18} \le n \le 10^{18}$
- $1 \le N \le 10^{12}$
- $1 \le K \le 10^9$
Examples
Example 1
Input: solve_subset_and_kth_factor([4, 2, 1, 10], 7, 12, 3)
Output: [3, 3]
Example 2
Input: solve_subset_and_kth_factor([-5, 2, 0, 3], 0, 16, 5)
Output: [4, 16]
Example 3
Input: solve_subset_and_kth_factor([3, 3, 3], 2, 36, 10)
Output: [0, -1]
Hints
Hint 1
Including all negative numbers decreases the total running sum as much as possible, which allows you to include all of them while maximizing your budget for positive numbers.
Hint 2
Zeros add 0 to the sum, so every zero in arr can always be included whenever all negative numbers fit into the budget.
Hint 3
If sum(negatives) <= n, the optimal subset takes all negatives, all zeros, and then picks the smallest positive elements one by one until adding the next positive element would push the total sum over n.
Hint 4
If sum(negatives) > n, even the minimal sum subset (all negatives) exceeds n, so 0 elements can be chosen (or no subset of all negatives + zeros can satisfy <= n).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires solving two distinct components:
1. Maximum Subset Count
To maximize the number of elements picked from arr such that their total sum is $\le n$:
- Negative numbers: Any negative number reduces the overall sum. Thus, picking all negative numbers minimizes the subset sum and maximizes the count of chosen elements.
- Zeros: Zeros increase the count of chosen elements without changing the sum.
- Positive numbers: After taking all negative numbers and all zeros, if the sum of negative numbers
sum_negis $\le n$, we have a remaining sum budget of $n - \text{sum_neg}$. We greedily take positive numbers in ascending order until the remaining budget cannot accommodate the next positive number. - Edge case (
sum_neg > n): If the sum of all negative numbers already exceeds $n$, even the subset with the smallest possible sum (all negatives) has a sum $> n$. Any non-empty subset containing fewer negatives would have a strictly greater sum, so no subset of negative numbers can achieve a sum $\le n$ unless we take zero elements (sum = $0 > n$, which fails if $n < 0$). Hence,max_countis $0$.
2. $K$-th Divisor of $N$
To find the $K$-th smallest factor of $N$:
- Iterate $d$ from $1$ to $\lfloor\sqrt{N}\rfloor$.
- If $d$ divides $N$, append $d$ to a list
small, and if $d^2 \neq N$, append $N // d$ to a listlarge. - Concatenate
smallandlargein reverse order to get all factors of $N$ in sorted order. - Return the $K$-th element (1-indexed), or
-1if $K > \text{len}(\text{factors})$.
Complexity Analysis
- Subset Count: $O(L \log L)$ time to sort non-negative numbers where $L = |arr|$, and $O(L)$ space.
- $K$-th Divisor: $O(\sqrt{N})$ time and $O(d(N))$ space, where $d(N)$ is the number of divisors of $N$.
- Total Time Complexity: $O(L \log L + \sqrt{N})$.
- Total Space Complexity: $O(L + d(N))$.
Python 3 Reference Solution
from typing import List
from math import isqrt
def solve_subset_and_kth_factor(arr: List[int], n: int, N: int, K: int) -> List[int]:
negatives = [x for x in arr if x < 0]
nonnegative = sorted(x for x in arr if x >= 0)
sum_neg = sum(negatives)
if sum_neg > n:
count = 0
else:
remaining = n - sum_neg
count = len(negatives) + sum(1 for x in nonnegative if x == 0)
for x in nonnegative:
if x == 0:
continue
if x <= remaining:
remaining -= x
count += 1
else:
break
small = []
large = []
for d in range(1, isqrt(N) + 1):
if N % d == 0:
small.append(d)
if d * d != N:
large.append(N // d)
factors = small + large[::-1]
kth = factors[K - 1] if K <= len(factors) else -1
return [count, kth]