출처 : https://leetcode.com/problems/longest-subsequence-with-limited-sum/
You are given an integer array nums
of length n
, and an integer array queries
of length m
.
Return an array answer
of length m
where answer[i]
is the maximum size of a subsequence that you can take from nums
such that the sum of its elements is less than or equal to queries[i]
.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
class Solution {
public int[] answerQueries(int[] nums, int[] queries) {
List<Integer> numbers = new ArrayList<>();
for (int q : nums) numbers.add(q);
Collections.sort(numbers);
int[] answer = new int[queries.length];
int qInd = 0;
while (qInd < queries.length) {
int limit = queries[qInd];
int count = 0;
for (int n = 0; n < numbers.size(); n++) {
if (limit - numbers.get(n) >= 0) {
limit -= numbers.get(n);
count++;
} else break;
}
answer[qInd++] = count;
}
return answer;
}
}