From 2f2122f63157471fc9f23d158f24fb28ff45ba40 Mon Sep 17 00:00:00 2001 From: vidhirohira <159313286+vidhirohira@users.noreply.github.com> Date: Mon, 21 Oct 2024 19:02:22 +0530 Subject: [PATCH] Create potd- 21_10_2024.cpp added ptod 21_10_2024 with comments --- october_2024/potd- 21_10_2024.cpp | 42 +++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 october_2024/potd- 21_10_2024.cpp diff --git a/october_2024/potd- 21_10_2024.cpp b/october_2024/potd- 21_10_2024.cpp new file mode 100644 index 0000000..8e61190 --- /dev/null +++ b/october_2024/potd- 21_10_2024.cpp @@ -0,0 +1,42 @@ +class Solution { +public: + // Main function to find the maximum number of unique substrings + int maxUniqueSplit(string s) { + unordered_set seen; // Set to store unique substrings + int maxCount = 0; // Variable to store the maximum count of unique substrings + + // Call the backtracking function to find the maximum count + backtrack(s, 0, seen, 0, maxCount); + + return maxCount; // Return the final result + } + +private: + // Backtracking function to explore all possible splits + void backtrack(const string& s, int start, unordered_set& seen, + int count, int& maxCount) { + // Pruning: If the remaining characters plus current count can't exceed maxCount, return + if (count + (s.size() - start) <= maxCount) return; + + // Base case: If we've reached the end of the string + if (start == s.size()) { + maxCount = max(maxCount, count); // Update maxCount if necessary + return; + } + + // Try all possible substrings starting from 'start' + for (int end = start + 1; end <= s.size(); ++end) { + string substring = s.substr(start, end - start); // Extract substring + + // If the substring is not in the set (i.e., it's unique) + if (seen.find(substring) == seen.end()) { + seen.insert(substring); // Add the substring to the set + + // Recursively call backtrack with updated parameters + backtrack(s, end, seen, count + 1, maxCount); + + seen.erase(substring); // Remove the substring from the set (backtracking) + } + } + } +};