KatInterview

Subset Count Under Sum Constraint and Divisor Index

Math & Bit ManipulationAuto-graded · 23 test cases

Last 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]:

  1. max_count: The maximum number of elements you can select from arr such that the sum of the selected elements is less than or equal to n.

    • You can choose any subset of indices from arr (including the empty subset, which has sum 0 and count 0, or the full set of elements).
    • If the sum of all negative numbers in arr is already greater than n (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$, return 0.
  2. kth_divisor: The $K$-th smallest positive integer divisor of N (1-indexed). If N has fewer than K positive 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).