LeetCode in Kotlin

2389. Longest Subsequence With Limited Sum

Easy

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.

Example 1:

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

Output: [2,3,4]

Explanation: We answer the queries as follows:

Example 2:

Input: nums = [2,3,4,5], queries = [1]

Output: [0]

Explanation: The empty subsequence is the only subsequence that has a sum less than or equal to 1, so answer[0] = 0.

Constraints:

Solution

class Solution {
    fun answerQueries(nums: IntArray, queries: IntArray): IntArray {
        // we can sort the nums because the order of the subsequence does not matter
        nums.sort()
        for (i in 1 until nums.size) {
            nums[i] = nums[i] + nums[i - 1]
        }
        for (i in queries.indices) {
            var j = nums.binarySearch(queries[i])
            if (j < 0) {
                j = -j - 2
            }
            queries[i] = j + 1
        }
        return queries
    }
}