{ "data": { "question": { "questionId": "3233", "questionFrontendId": "3003", "boundTopicId": null, "title": "Maximize the Number of Partitions After Operations", "titleSlug": "maximize-the-number-of-partitions-after-operations", "content": "

You are given a 0-indexed string s and an integer k.

\n\n

You are to perform the following partitioning operations until s is empty:

\n\n\n\n

Before the operations, you are allowed to change at most one index in s to another lowercase English letter.

\n\n

Return an integer denoting the maximum number of resulting partitions after the operations by optimally choosing at most one index to change.

\n

 

\n

Example 1:

\n\n
\nInput: s = "accca", k = 2\nOutput: 3\nExplanation: In this example, to maximize the number of resulting partitions, s[2] can be changed to 'b'.\ns becomes "acbca".\nThe operations can now be performed as follows until s becomes empty:\n- Choose the longest prefix containing at most 2 distinct characters, "acbca".\n- Delete the prefix, and s becomes "bca". The number of partitions is now 1.\n- Choose the longest prefix containing at most 2 distinct characters, "bca".\n- Delete the prefix, and s becomes "a". The number of partitions is now 2.\n- Choose the longest prefix containing at most 2 distinct characters, "a".\n- Delete the prefix, and s becomes empty. The number of partitions is now 3.\nHence, the answer is 3.\nIt can be shown that it is not possible to obtain more than 3 partitions.
\n\n

Example 2:

\n\n
\nInput: s = "aabaab", k = 3\nOutput: 1\nExplanation: In this example, to maximize the number of resulting partitions we can leave s as it is.\nThe operations can now be performed as follows until s becomes empty: \n- Choose the longest prefix containing at most 3 distinct characters, "aabaab".\n- Delete the prefix, and s becomes empty. The number of partitions becomes 1. \nHence, the answer is 1. \nIt can be shown that it is not possible to obtain more than 1 partition.\n
\n\n

Example 3:

\n\n
\nInput: s = "xxyz", k = 1\nOutput: 4\nExplanation: In this example, to maximize the number of resulting partitions, s[1] can be changed to 'a'.\ns becomes "xayz".\nThe operations can now be performed as follows until s becomes empty:\n- Choose the longest prefix containing at most 1 distinct character, "xayz".\n- Delete the prefix, and s becomes "ayz". The number of partitions is now 1.\n- Choose the longest prefix containing at most 1 distinct character, "ayz".\n- Delete the prefix, and s becomes "yz". The number of partitions is now 2.\n- Choose the longest prefix containing at most 1 distinct character, "yz".\n- Delete the prefix, and s becomes "z". The number of partitions is now 3.\n- Choose the longest prefix containing at most 1 distinct character, "z".\n- Delete the prefix, and s becomes empty. The number of partitions is now 4.\nHence, the answer is 4.\nIt can be shown that it is not possible to obtain more than 4 partitions.\n
\n\n

 

\n

Constraints:

\n\n\n", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Hard", "likes": 58, "dislikes": 12, "isLiked": null, "similarQuestions": "[{\"title\": \"Can Make Palindrome from Substring\", \"titleSlug\": \"can-make-palindrome-from-substring\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "exampleTestcases": "\"accca\"\n2\n\"aabaab\"\n3\n\"xxyz\"\n1", "categoryTitle": "Algorithms", "contributors": [], "topicTags": [ { "name": "String", "slug": "string", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Dynamic Programming", "slug": "dynamic-programming", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Bit Manipulation", "slug": "bit-manipulation", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Bitmask", "slug": "bitmask", "translatedName": null, "__typename": "TopicTagNode" } ], "companyTagStats": null, "codeSnippets": [ { "lang": "C++", "langSlug": "cpp", "code": "class Solution {\npublic:\n int maxPartitionsAfterOperations(string s, int k) {\n \n }\n};", "__typename": "CodeSnippetNode" }, { "lang": "Java", "langSlug": "java", "code": "class Solution {\n public int maxPartitionsAfterOperations(String s, int k) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Python", "langSlug": "python", "code": "class Solution(object):\n def maxPartitionsAfterOperations(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: int\n \"\"\"\n ", "__typename": "CodeSnippetNode" }, { "lang": "Python3", "langSlug": "python3", "code": "class Solution:\n def maxPartitionsAfterOperations(self, s: str, k: int) -> int:\n ", "__typename": "CodeSnippetNode" }, { "lang": "C", "langSlug": "c", "code": "int maxPartitionsAfterOperations(char* s, int k) {\n \n}", "__typename": "CodeSnippetNode" }, { "lang": "C#", "langSlug": "csharp", "code": "public class Solution {\n public int MaxPartitionsAfterOperations(string s, int k) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "JavaScript", "langSlug": "javascript", "code": "/**\n * @param {string} s\n * @param {number} k\n * @return {number}\n */\nvar maxPartitionsAfterOperations = function(s, k) {\n \n};", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "function maxPartitionsAfterOperations(s: string, k: number): number {\n \n};", "__typename": "CodeSnippetNode" }, { "lang": "PHP", "langSlug": "php", "code": "class Solution {\n\n /**\n * @param String $s\n * @param Integer $k\n * @return Integer\n */\n function maxPartitionsAfterOperations($s, $k) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Swift", "langSlug": "swift", "code": "class Solution {\n func maxPartitionsAfterOperations(_ s: String, _ k: Int) -> Int {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Kotlin", "langSlug": "kotlin", "code": "class Solution {\n fun maxPartitionsAfterOperations(s: String, k: Int): Int {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Dart", "langSlug": "dart", "code": "class Solution {\n int maxPartitionsAfterOperations(String s, int k) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Go", "langSlug": "golang", "code": "func maxPartitionsAfterOperations(s string, k int) int {\n \n}", "__typename": "CodeSnippetNode" }, { "lang": "Ruby", "langSlug": "ruby", "code": "# @param {String} s\n# @param {Integer} k\n# @return {Integer}\ndef max_partitions_after_operations(s, k)\n \nend", "__typename": "CodeSnippetNode" }, { "lang": "Scala", "langSlug": "scala", "code": "object Solution {\n def maxPartitionsAfterOperations(s: String, k: Int): Int = {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Rust", "langSlug": "rust", "code": "impl Solution {\n pub fn max_partitions_after_operations(s: String, k: i32) -> i32 {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Racket", "langSlug": "racket", "code": "(define/contract (max-partitions-after-operations s k)\n (-> string? exact-integer? exact-integer?)\n )", "__typename": "CodeSnippetNode" }, { "lang": "Erlang", "langSlug": "erlang", "code": "-spec max_partitions_after_operations(S :: unicode:unicode_binary(), K :: integer()) -> integer().\nmax_partitions_after_operations(S, K) ->\n .", "__typename": "CodeSnippetNode" }, { "lang": "Elixir", "langSlug": "elixir", "code": "defmodule Solution do\n @spec max_partitions_after_operations(s :: String.t, k :: integer) :: integer\n def max_partitions_after_operations(s, k) do\n \n end\nend", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"1.3K\", \"totalSubmission\": \"5.7K\", \"totalAcceptedRaw\": 1286, \"totalSubmissionRaw\": 5662, \"acRate\": \"22.7%\"}", "hints": [ "For each position, try to brute-force the replacements.", "To speed up the brute-force solution, we can precompute the following (without changing any index) using prefix sums and binary search:", "Now, for a position i, we can try all possible 25 replacements:
\r\nFor a replacement, using prefix sums and binary search, we need to find the rightmost index, r, such that the number of distinct characters in the range [partition_start[i], r] is at most k.
\r\nThere are 2 cases:", "The answer is the maximum among all replacements." ], "solution": null, "status": null, "sampleTestCase": "\"accca\"\n2", "metaData": "{\n \"name\": \"maxPartitionsAfterOperations\",\n \"params\": [\n {\n \"name\": \"s\",\n \"type\": \"string\"\n },\n {\n \"type\": \"integer\",\n \"name\": \"k\"\n }\n ],\n \"return\": {\n \"type\": \"integer\"\n }\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "enableTestMode": false, "enableDebugger": true, "envInfo": "{\"cpp\": [\"C++\", \"

Compiled with clang 11 using the latest C++ 20 standard.

\\r\\n\\r\\n

Your code is compiled with level two optimization (-O2). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\"], \"java\": [\"Java\", \"

OpenJDK 21. Using compile arguments: --enable-preview --release 21

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n

Includes Pair class from https://docs.oracle.com/javase/8/javafx/api/javafx/util/Pair.html.

\"], \"python\": [\"Python\", \"

Python 2.7.12.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\\r\\n\\r\\n

Note that Python 2.7 will not be maintained past 2020. For the latest Python, please choose Python3 instead.

\"], \"c\": [\"C\", \"

Compiled with gcc 11 using the gnu11 standard.

\\r\\n\\r\\n

Your code is compiled with level one optimization (-O2). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n\\r\\n

For hash table operations, you may use uthash. \\\"uthash.h\\\" is included by default. Below are some examples:

\\r\\n\\r\\n

1. Adding an item to a hash.\\r\\n

\\r\\nstruct hash_entry {\\r\\n    int id;            /* we'll use this field as the key */\\r\\n    char name[10];\\r\\n    UT_hash_handle hh; /* makes this structure hashable */\\r\\n};\\r\\n\\r\\nstruct hash_entry *users = NULL;\\r\\n\\r\\nvoid add_user(struct hash_entry *s) {\\r\\n    HASH_ADD_INT(users, id, s);\\r\\n}\\r\\n
\\r\\n

\\r\\n\\r\\n

2. Looking up an item in a hash:\\r\\n

\\r\\nstruct hash_entry *find_user(int user_id) {\\r\\n    struct hash_entry *s;\\r\\n    HASH_FIND_INT(users, &user_id, s);\\r\\n    return s;\\r\\n}\\r\\n
\\r\\n

\\r\\n\\r\\n

3. Deleting an item in a hash:\\r\\n

\\r\\nvoid delete_user(struct hash_entry *user) {\\r\\n    HASH_DEL(users, user);  \\r\\n}\\r\\n
\\r\\n

\"], \"csharp\": [\"C#\", \"

C# 12 with .NET 8 runtime

\"], \"javascript\": [\"JavaScript\", \"

Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES6 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\\r\\n\\r\\n

For Priority Queue / Queue data structures, you may use 5.3.0 version of datastructures-js/priority-queue and 4.2.1 version of datastructures-js/queue.

\"], \"ruby\": [\"Ruby\", \"

Ruby 3.2

\\r\\n\\r\\n

Some common data structure implementations are provided in the Algorithms module: https://www.rubydoc.info/github/kanwei/algorithms/Algorithms

\"], \"swift\": [\"Swift\", \"

Swift 5.9.

\"], \"golang\": [\"Go\", \"

Go 1.21

\\r\\n

Support https://godoc.org/github.com/emirpasic/gods@v1.18.1 library.

\"], \"python3\": [\"Python3\", \"

Python 3.11.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\"], \"scala\": [\"Scala\", \"

Scala 2.13.7.

\"], \"kotlin\": [\"Kotlin\", \"

Kotlin 1.9.0.

\\r\\n\\r\\n

We are using an experimental compiler provided by JetBrains.

\"], \"rust\": [\"Rust\", \"

Rust 1.74.1

\\r\\n\\r\\n

Supports rand v0.6\\u00a0from crates.io

\"], \"php\": [\"PHP\", \"

PHP 8.2.

\\r\\n

With bcmath module

\"], \"typescript\": [\"Typescript\", \"

TypeScript 5.1.6, Node.js 16.13.2.

\\r\\n\\r\\n

Compile Options: --alwaysStrict --strictBindCallApply --strictFunctionTypes --target ES2022

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES2022 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\"], \"racket\": [\"Racket\", \"

Racket CS v8.11

\\r\\n\\r\\n

Using #lang racket

\\r\\n\\r\\n

Required data/gvector data/queue data/order data/heap automatically for your convenience

\"], \"erlang\": [\"Erlang\", \"Erlang/OTP 26\"], \"elixir\": [\"Elixir\", \"Elixir 1.15 with Erlang/OTP 26\"], \"dart\": [\"Dart\", \"

Dart 3.2

\\r\\n\\r\\n

Your code will be run directly without compiling

\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }