Longest Subsequence With Limited Sum

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 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.

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:

  1. Sort the input array and initialize an empty array ans .

  2. For each query i , traverse the sorted input array and collect numbers from lowest to highest. Keep incrementing a count variable until the sum exceeds the value of the query.

  3. Add count to answer.

  4. 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!