Prime Subset Selection I Problem
Description
LeetCode Problem 4079.
You are given two integers n and s.
Consider all prime numbers less than or equal to n. Select some of these primes such that:
- The sum of the selected primes is less than or equal to
s. - The number of selected primes is maximized.
- Each prime can be selected at most once.
Return an integer array containing the selected primes in increasing order. If multiple optimal selections exist, return any of them.
If no prime can be selected, return an empty array.
Example 1:
Input: n = 7, s = 20
Output: [2,3,5,7]
Explanation:
- The prime numbers less than or equal to n = 7 are 2, 3, 5, and 7.
- The sum of all these primes is 2 + 3 + 5 + 7 = 17, which is less than or equal to s = 20.
- Thus, the answer is [2, 3, 5, 7].
Example 2:
Input: n = 15, s = 15
Output: [3,5,7]
Explanation:
- The prime numbers less than or equal to n = 15 are 2, 3, 5, 7, 11, and 13.
- One possible selection is [3, 5, 7], whose sum is 3 + 5 + 7 = 15.
- The four smallest available primes have sum 2 + 3 + 5 + 7 = 17, which exceeds s = 15. Therefore, selecting four or more primes is impossible, and the maximum number of selected primes is three.
- Thus, [3, 5, 7] is one possible answer. Other valid answers include [2, 3, 5], [2, 3, 7], and [2, 5, 7].
Example 3:
Input: n = 5, s = 1
Output: []
Explanation:
- The smallest prime number is 2, which is greater than s = 1.
- Thus, no prime can be selected, so the answer is an empty array.
Constraints:
1 <= n <= 10^61 <= s <= 10^9
Solution
Approach: Sieve and greedy
Among all subsets with the same number of primes, the one made of the smallest primes has the smallest sum. So to maximize the count, take the smallest primes, in increasing order, as long as they are at most n and the remaining budget allows them.
Build the list of primes up to 10^6 once with the sieve of Eratosthenes. For a query, walk through the list: stop as soon as the prime is greater than n or greater than the remaining s; otherwise add it to the answer and subtract it from s. Other optimal selections exist, and any of them is accepted.
Complexity: the sieve costs O(M log log M) time and O(M) space (M = 10^6); a query costs O(pi(n)), where pi(n) is the number of primes up to n.
mx = 10**6
primes = []
is_prime = [True] * (mx + 1)
is_prime[0] = is_prime[1] = False
for i in range(2, mx + 1):
if is_prime[i]:
primes.append(i)
if i * i <= mx:
for j in range(i * i, mx + 1, i):
is_prime[j] = False
class Solution:
def maxPrimes(self, n: int, s: int) -> List[int]:
ans = []
for p in primes:
if p > n or p > s:
break
ans.append(p)
s -= p
return ans