From bb11a352271401bb46281d109759202520ff9e31 Mon Sep 17 00:00:00 2001 From: Alexander Pantyukhin Date: Fri, 2 Dec 2022 08:55:36 +0400 Subject: [PATCH] feat: add Maximize the Confusion LeetCode problem (#1150) * add Maximize the Confusion of an Exam leetcode * Update leetcode/src/2024.c Co-authored-by: Taj * Update 2024.c fix build Co-authored-by: Taj --- leetcode/DIRECTORY.md | 1 + leetcode/src/2024.c | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 leetcode/src/2024.c diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index d02cf7ad..da623564 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -103,5 +103,6 @@ | 1524 | [Number of Sub-arrays With Odd Sum](https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/) | [C](./src/1524.c) | Medium | | 1653 | [Minimum Deletions to Make String Balanced](https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/) | [C](./src/1653.c) | Medium | | 1752 | [Check if Array Is Sorted and Rotated](https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/) | [C](./src/1752.c) | Easy | +| 2024 | [Maximize the Confusion of an Exam](https://leetcode.com/problems/maximize-the-confusion-of-an-exam/) | [C](./src/2024.c) | Medium | | 2130 | [Maximum Twin Sum of a Linked List](https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/) | [C](./src/2130.c) | Medium | | 2304 | [Minimum Path Cost in a Grid](https://leetcode.com/problems/minimum-path-cost-in-a-grid/) | [C](./src/2304.c) | Medium | diff --git a/leetcode/src/2024.c b/leetcode/src/2024.c new file mode 100644 index 00000000..5796f0b0 --- /dev/null +++ b/leetcode/src/2024.c @@ -0,0 +1,33 @@ +#define max(X, Y) ((X) > (Y) ? (X) : (Y)) + +int maximizeTarget(char * answerKey, char targetChar, int k){ + int leftIndex = -1; + int result = 0; + int currTargetChars = 0; + int lenAnswerKey = strlen(answerKey); + + for (int rightIndex = 0; rightIndex < lenAnswerKey; rightIndex++){ + char ch = answerKey[rightIndex]; + if (ch == targetChar){ + currTargetChars++; + } + + while (rightIndex - leftIndex > currTargetChars + k) { + leftIndex++; + if (answerKey[leftIndex] == targetChar){ + currTargetChars--; + } + } + + result = max(result, rightIndex - leftIndex); + } + + return result; +} + +// Use sliding window approach + two pointers. +// Runtime: O(n) +// Space: O(1) +int maxConsecutiveAnswers(char * answerKey, int k){ + return max(maximizeTarget(answerKey, 'T', k), maximizeTarget(answerKey, 'F', k)); +}