2389. Longest Subsequence With Limited Sum

2023. 1. 24. 17:47Algorithm/Leetcode, Lintcode, HackerRank, etc.

    목차
반응형

Python

class Solution:
    def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
        incs = []
        nums.sort()

        for num in nums:
            if incs:
                incs += incs[-1] + num,
            else:
                incs += num,

        res = []
        for query in queries:
            idx = bisect.bisect_left(incs, query)
            if idx < len(incs) and incs[idx] == query:
                res += idx + 1,
            else:
                res += idx,

        return res

Kotlin

class Solution {
    fun answerQueries(nums: IntArray, queries: IntArray): IntArray {
        var list: MutableList<Int> = mutableListOf()
        nums.sort()

        for (num in nums) {
            if (list.size > 0) {
                list.add(list[list.size - 1] + num)
            } else {
                list.add(num)
            }
        }

        var res: MutableList<Int> = mutableListOf()

        for (query in queries) {
            val idx: Int = list.binarySearch(query)
            if (idx < 0) {
                res.add(-(idx + 1))
            } else {
                res.add(idx + 1)
            }
        }

        return res.toIntArray()
    }
}
반응형