LC 2790. 长度递增组的最大数目

https://leetcode.cn/problems/maximum-number-of-groups-with-increasing-length/description/

我看了题解里面两种解法,感觉都挺好的

二分的思路就是检查K个长度是否可以达到,我们可以从最大的往前填补:

Pasted-Image-20231225104310.png

Pasted-Image-20231225104235.png

class Solution:
    def maxIncreasingGroups(self, usageLimits: List[int]) -> int:
        usageLimits.sort(reverse=True)

        def test(K):
            gap = 0
            for x in usageLimits:
                gap = min(gap + x - K, 0) # 只使用当前值去填充,之前多出来的会回填到之前的空处。
                # 因为我们这里是从大到小填充,所以肯定不会出现重叠的情况。
                if K > 0:
                    K -= 1
            return gap >= 0

        s, e = 1, len(usageLimits)
        while s <= e:
            k = (s + e) // 2
            if test(k):
                s = k + 1
            else:
                e = k - 1
        return e

贪心则是从小到大进行填充:

class Solution:
    def maxIncreasingGroups(self, usageLimits: List[int]) -> int:
        usageLimits.sort()
        xs = usageLimits.copy()
        n = len(xs)
        xs.append(0)

        ans = 1
        for i in range(n):
            if xs[i] >= ans:
                xs[i] -= ans
                ans += 1
            xs[i + 1] += xs[i]
        return ans - 1