Leetcode 2389: Longest Subsequence With Limited Sum

grid47
grid47
Exploring patterns and algorithms
Mar 13, 2024 5 min read

You are given an integer array nums of length n and an integer array queries of length m. For each query, return the maximum size of a subsequence that can be selected from nums such that the sum of its elements is less than or equal to the query value. A subsequence is derived by deleting some or no elements from the array while keeping the relative order intact.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array `nums` and an integer array `queries`.
Example: Input: nums = [1,3,5,7], queries = [6,12,18]
Constraints:
• n == nums.length
• m == queries.length
• 1 <= n, m <= 1000
• 1 <= nums[i], queries[i] <= 10^6
Output: For each query, return the maximum size of the subsequence such that its sum is less than or equal to the query value.
Example: Output: [2, 3, 4]
Constraints:
Goal: The goal is to find the maximum size of the subsequence for each query where the sum does not exceed the query value.
Steps:
• 1. Sort the array `nums` to easily select the smallest elements first.
• 2. Compute the prefix sum of the sorted array to get the cumulative sum of elements.
• 3. For each query, use binary search to find the maximum number of elements whose sum is less than or equal to the query value.
Goal: Ensure the solution works efficiently within the provided constraints.
Steps:
• The array `nums` can have up to 1000 elements.
• Each element of `nums` and each query value is between 1 and 10^6.
Assumptions:
• Queries are independent and each query needs to be answered individually.
Input: Input: nums = [1, 3, 5, 7], queries = [6, 12, 18]
Explanation: For the query 6, the subsequence [1, 3] has a sum of 4, which is the largest subsequence with a sum <= 6, hence the answer is 2. For the query 12, the subsequence [1, 3, 5] has a sum of 9, and for 18, the subsequence [1, 3, 5, 7] has a sum of 16, so the answers are [2, 3, 4].

Input: Input: nums = [2, 4, 6, 8], queries = [5]
Explanation: For the query 5, the largest subsequence with a sum <= 5 is [2], so the answer is 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus