考试的最大困扰度 leetcode java篇

news/2024/7/8 5:23:50

一位老师正在出一场由 n 道判断题构成的考试,每道题的答案为 true (用 'T' 表示)或者 false (用 'F' 表示)。老师想增加学生对自己做出答案的不确定性,方法是 最大化 有 连续相同 结果的题数。(也就是连续出现 true 或者连续出现 false)。

给你一个字符串 answerKey ,其中 answerKey[i] 是第 i 个问题的正确结果。除此以外,还给你一个整数 k ,表示你能进行以下操作的最多次数:

每次操作中,将问题的正确答案改为 'T' 或者 'F' (也就是将 answerKey[i] 改为 'T' 或者 'F' )。
请你返回在不超过 k 次操作的情况下,最大 连续 'T' 或者 'F' 的数目。

 

 

class Solution {
    public int maxConsecutiveAnswers(String answerKey, int k) {
        return Math.max(getCnt(answerKey, 'T', k), getCnt(answerKey, 'F', k));
    }

    public int getCnt(String s, char c, int k) {
        int n = s.length();
        int count = 0;
        int ret = 0;
        for (int i = 0, j = 0; i < n; i++) {
            if (s.charAt(i) == c) {
                count++;
            }
            while (count > k) {
                if (s.charAt(j) == c) {
                    count--;
                }
                j++;
            }
            ret = Math.max(ret, i - j + 1);
        }
        return ret;
    }
}

 

 


http://www.niftyadmin.cn/n/3651724.html

相关文章

Lonely Low

Have you ever been this lowthat you dont know where to go?Missing something you do long for,trying to get to heaven before they close the door?You walk slowly along the beach,seeing the sands of time sort of etch.You look around -- the sea is blue,shout …

SHAKESPEARE SONNETS LXVI

性能测试常见误区请看下面一个性能测试小案例&#xff1a;某公司OA产品的新版本即将发布。为了看看系统的性能&#xff0c;决定安排测试工程师A君执行性能测试任务。A君做法如下&#xff1a;1. 找到一台PC机&#xff0c;CPU主频1G&#xff0c;内存512M&#xff0c;……&a…

动态规划系列(1) leetcode java

第一题: 斐波那契数 &#xff08;通常用 F(n) 表示&#xff09;形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始&#xff0c;后面的每一项数字都是前面两项数字的和。也就是&#xff1a; 核心思想: F(n)F(n−1)F(n−2) class Solution {public int fib(int n) {int f0 …

FEW MORE CUPS OF COFFEE铪铪

AUG.2,2005FEW MORE CUPS OF COFFEEby Kakuji FunegataDo I have to remind you,Whom I owe cups of coffee to ?I am and will be forever in your debtUntil I do you the favor at last.Is it alright that you I inviteTo have some coffee at any time you like ?To the…

动态规划系列(2) leetcode java

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢&#xff1f; class Solution {public int climbStairs(int n) {int s 0;int e 1;int tmp 0;while(n-->0){tmp e;es;s tmp;}return e;} } 第二题: 给你…

买卖股票的最佳时机 leetcode java篇

给定一个数组 prices &#xff0c;它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天 买入这只股票&#xff0c;并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。 返回你可以从这笔交易中获取的最大利润。…

动态规划系列(3) leetcode java篇

第一题: 打家劫舍 你是一个专业的小偷&#xff0c;计划偷窃沿街的房屋。每间房内都藏有一定的现金&#xff0c;影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统&#xff0c;如果两间相邻的房屋在同一晚上被小偷闯入&#xff0c;系统会自动报警。 给定一个代表…

动态规划系列(4) leetcode Java篇

第一题: 跳跃游戏 给定一个非负整数数组 nums &#xff0c;你最初位于数组的 第一个下标 。 数组中的每个元素代表你在该位置可以跳跃的最大长度。 判断你是否能够到达最后一个下标。 class Solution {public boolean canJump(int[] num) {int len num.length;if(len1){re…