Given an array of positive integers nums and an integer k, return the maximum number of elements you can select from nums such that their sum is strictly less than k.
You may select any subset of elements (order does not matter), but the total sum of the selected elements must stay less than k.
Function Signature
def max_elements_with_sum_less_than_k(nums: list[int], k: int) -> int:
Rules
-
Each array position can be selected at most once. Equal values at different positions count as separate elements.
-
The selected elements do not need to be next to each other in the array.
-
If even the smallest element is not less than
k
, return 0.
Constraints
-
1 <= nums.length <= 10^5
-
1 <= nums[i] <= 10^4
-
1 <= k <= 10^9
Examples
Input: nums = [1,2,3,4,5], k = 10
Output: 3
Picking 1, 2 and 3 gives a sum of 6, which is below 10. Any four elements sum to at least 1 + 2 + 3 + 4 = 10, which is not strictly less than 10, so the answer is 3.
Input: nums = [5,5,5,5], k = 7
Output: 1
A single 5 is below 7. Any two elements sum to 10, which is at least 7, so the answer is 1.