Table of contents
Hello and welcome back to the Leetcode Daily Series! We have a very simple problem ahead of us today, although identifying the trick needed to solve it might prove a bit difficult.
Let's get started!
Understanding The Problem
Let's take a look at the problem statement first.
You are given an integer array
nums
of lengthn
, and an integer arrayqueries
of lengthm
.Return an array
answer
of lengthm
whereanswer[i]
is the maximum size of a subsequence that you can take fromnums
such that the sum of its elements is less than or equal toqueries[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.
The task is pretty clear, but the path to the solution, not so much.
Try to solve the following examples yourself to make sure you understand the problem.
Input: nums = [4,5,2,1], queries = [3,10,21]
Input: nums = [2,3,4,5], queries = [1]
What will be the output for these inputs? If you're getting [2,3,4]
and [0]
respectively, you've grasped the problem.
Intuition
One very simple observation will make solving this problem a piece of cake. Normally, when we hear the word subsequence, the thought that enters our minds is that continuity doesn't matter, but the order of elements does.
However, in this problem, we can ignore the order of elements too! Since we only need to compare the sum of the subsequence with the value of the query.
Since we can ignore the order of the elements, why not sort the input array? That will make our job a lot easier.
For each query, we need to maximize the size of the subsequence before its sum exceeds the value of the query. So, it makes sense to start from the smallest numbers.
The algorithm will look something like this:
Sort the input array and initialize an empty array
ans
.For each query
i
, traverse the sorted input array and collect numbers from lowest to highest. Keep incrementing acount
variable until the sum exceeds the value of the query.Add
count
to answer.Return
ans
.
Coding Up The Steps
Here's the full solution to this problem.
class Solution {
public:
vector<int> answerQueries(vector<int>& nums, vector<int>& queries) {
sort(nums.begin(),nums.end());
vector<int> ans;
for(int i : queries){
int count = 0;
for(int n : nums){
if(i >= n){
i -= n;
count++;
}
else{
break;
}
}
ans.push_back(count);
}
return ans;
}
};
That's it for today! See you tomorrow(hopefully).
Cheers!