![]() |
VOOZH | about |
Given a string S of size N consisting of numerical digits 1-9 and a positive integer K, the task is to minimize the partitions of the string such that each part is at most K. If it’s impossible to partition the string print -1.
Examples:
Input: S = "3456", K = 45
Output: 2
Explanation: One possible way is to partition as 3, 45, 6.
Another possibility is 3, 4, 5, 6, which uses 3 partition.
No configuration needs less than 2 partitions. Hence, the answer is 2.Input: S = "7891634", K = 21
Output: 5
Explanation: The minimum number of partitions is
7, 8, 9, 16, 3, 4, which uses 5 partitions.Input: S = "67142849", K = 39
Output: 5
Approach: The approach to this problem is based on the below idea:
Make each partition have a value as large as possible with an upper limit of K.
An edge case is if it’s impossible to partition the string. It will happen if the maximum digit in the string is larger than K..
Follow the below steps to solve this problem:
Below is the implementation of the above approach:
5
Time Complexity: O(N)
Auxiliary Space: O(1)