![]() |
VOOZH | about |
Given a string str, the task is to partition the string into two substrings such that the sum of unique characters of both substrings is the maximum possible.
Examples:
Input: str = "abcabcd”
Output: 7
Explanation: Partition the given string into "abc" and "abcd", the sum of unique characters is 3 + 4 = 7 which is maximum possible.Input: str = "aaaaa”
Output: 2
Explanation: Partition the given string into "aa" and "aaa", the sum of unique characters is 1 + 1 = 2 which is maximum possible. Given string can be partitioned into many other ways but this partition gives the maximum sum of unique characters.
Approach: This problem can easily be solved using prefix and suffix arrays.
We can create a prefix array which will store the count of unique characters starting from index 0 to last index of the string. Similarly, We can create a suffix array which will store the count of unique characters starting from the last index to 0th index. Here, set can be used to check if the current character appeared before in the iterated string or not. We can calculate the maximum sum by doing prefix[i-1] + suffix[i] for each 1 <= i < n. Take prefix[i-1] + suffix[i] so that intersecting point never counts.
Follow the steps mentioned below to implement the idea:
Below is the implementation of the above approach.
Maximum value is 7
Time Complexity: O(N)
Auxiliary Space: O(N)
Efficient Approach: To solve this problem, we will use two Hash Maps and do the below steps:
Implementation of the approach:
Output:
Maximum sum is 7
Time Complexity: O(N)
Auxiliary Space: Constant space is used as there can be only at most 26 characters stored in hash map.