Leetcode 3085. Minimum Deletions to Make String K-Special

  • [Leetcode 3085. Minimum Deletions to Make String K-Special](#Leetcode 3085. Minimum Deletions to Make String K-Special)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题思路上来说的话我们只需要统计一下word当中所有的字符出现的频次,然后依次排序,我们只需要考察各个删除方案使得所有存在的频次之间的差值不多于 k k k即可。

而对于各个具体的删除方案的考察,我们只需要用一个滑动窗口来考察一下一下各个字母作为起点时允许的频次范围并计算一下对应方案下所需要删除的元素个数即可。

显然,对于任意时刻,左边界左侧的字符全部不采用,而右边界右侧的元素则全部替换为范围上界即可。

且不难看出,左右边界的移动必然都是单调的。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def minimumDeletions(self, word: str, k: int) -> int:
        n = len(word)
        cnt = Counter(word)
        cnt = sorted(cnt.values())
        i,j,m = 0,0,len(cnt)
        ans, s = n, 0
        while i < m:
            while j < m and cnt[j]-cnt[i] <= k:
                s += cnt[j]
                j += 1
            ans = min(ans, n-(s+(cnt[i]+k)*(m-j)))
            s -= cnt[i]
            i += 1
        return ans

提交代码评测得到:耗时93ms,占用内存17.6MB。

相关推荐
硕风和炜2 天前
【LeetCode:3101. 交替子数组计数 + 滑动窗口 + 数学公式】
java·数学·算法·leetcode·滑动窗口
linweidong5 天前
Flink 时间窗口在 IoT 项目中的应用实战
物联网·flink·iot·滚动窗口·滑动窗口·时间窗口
Espresso Macchiato6 天前
Leetcode 3201. Find the Maximum Length of Valid Subsequence I
leetcode medium·leetcode题解·leetcode 3201·leetcode周赛404
源代码:趴菜11 天前
leetcode209:长度最小的子数组
算法·leetcode·滑动窗口
Espresso Macchiato13 天前
Leetcode 3196. Maximize Total Cost of Alternating Subarrays
leetcode·动态规划·leetcode medium·leetcode周赛403·leetcode 3196
Espresso Macchiato14 天前
Leetcode 3195. Find the Minimum Area to Cover All Ones I
leetcode·leetcode medium·leetcode题解·leetcode 3195·leetcode周赛403
Espresso Macchiato22 天前
Leetcode 3186. Maximum Total Damage With Spell Casting
动态规划·leetcode medium·leetcode题解·leetcode 3186·leetcode周赛402
Espresso Macchiato1 个月前
Leetcode 3175. Find The First Player to win K Games in a Row
leetcode medium·leetcode题解·leetcode 3175·leetcode双周赛132
DogDaoDao1 个月前
LeetCode 算法:滑动窗口最大值c++
数据结构·c++·算法·leetcode·双端队列·滑动窗口·队列
小程xy1 个月前
leetcode力扣 2024. 考试的最大困扰度
数据结构·c++·算法·leetcode·滑动窗口