Taro Logo

Longest Subsequence With Limited Sum

Easy
Meta logo
Meta
1 view
Topics:
ArraysGreedy AlgorithmsBinary Search

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.

For example:

  • nums = [4, 5, 2, 1], queries = [3, 10, 21]

    The output should be [2, 3, 4].

    Explanation:

    • For query 3, the subsequence [2, 1] has a sum less than or equal to 3. The maximum size is 2.
    • For query 10, the subsequence [4, 5, 1] has a sum less than or equal to 10. The maximum size is 3.
    • For query 21, the subsequence [4, 5, 2, 1] has a sum less than or equal to 21. The maximum size is 4.
  • nums = [2, 3, 4, 5], queries = [1]

    The output should be [0].

    Explanation:

    • For query 1, the empty subsequence is the only subsequence with a sum less than or equal to 1. The maximum size is 0.

What is the most efficient algorithm to solve this problem?

Solution


Naive Approach

A brute-force solution would involve generating all possible subsequences of nums for each query in queries, calculating the sum of each subsequence, and checking if the sum is less than or equal to the current query value. The maximum size of a subsequence meeting the criteria is then the answer for that query.

Code (Python)

def max_subsequence_naive(nums, queries):
    n = len(nums)
    m = len(queries)
    answer = []

    for query in queries:
        max_size = 0
        for i in range(1 << n):  # Iterate through all possible subsequences
            subsequence = []
            subsequence_sum = 0

            for j in range(n):
                if (i >> j) & 1:  # Check if the j-th element is included in the subsequence
                    subsequence.append(nums[j])
                    subsequence_sum += nums[j]

            if subsequence_sum <= query:
                max_size = max(max_size, len(subsequence))

        answer.append(max_size)

    return answer

Time Complexity

The time complexity of this approach is O(m * 2n * n), where 'm' is the number of queries and 'n' is the number of elements in nums. For each query, we generate all possible subsequences (2n), and for each subsequence, we compute the sum in O(n) time.

Space Complexity

The space complexity is O(1) excluding the output array. We only use a constant amount of extra space.

Optimal Approach

The optimal approach involves sorting the nums array and then iterating through the sorted array to find the maximum subsequence size for each query. Because the numbers are sorted, we can greedily take elements from smallest to largest until we exceed the query value.

Code (Python)

def max_subsequence(nums, queries):
    nums.sort()
    n = len(nums)
    m = len(queries)
    answer = []

    for query in queries:
        current_sum = 0
        count = 0
        for i in range(n):
            if current_sum + nums[i] <= query:
                current_sum += nums[i]
                count += 1
            else:
                break
        answer.append(count)

    return answer

Time Complexity

The time complexity is dominated by sorting the nums array, which takes O(n log n) time. The iteration through the sorted array for each query takes O(n) time. Therefore, the overall time complexity is O(n log n + m * n), where 'n' is the number of elements in nums and 'm' is the number of queries.

Space Complexity

The space complexity is O(1) excluding the output array. Sorting nums is done in place or uses O(log n) space depending on the sorting algorithm.

Edge Cases

  • Empty nums array: If nums is empty, the answer for all queries will be 0.
  • All elements in nums are greater than the query: The answer will be 0.
  • Query is 0: The answer will be 0, as no positive numbers can be included in the subsequence.
  • Large query: If a query is very large, the subsequence can include almost all numbers from the nums array.