Sponsored
Sponsored
This approach involves iterating through the string, checking every possible substring of length 3 to see if it consists of the same character. If it does, keep track of the largest such substring found.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), constant space is used.
1#include <stdio.h>
2#include <string.h>
3
4char* largestGoodInteger(char* num) {
5 char maxGood[4] = "";
6 int n = strlen(num);
7 for (int i = 0; i <= n - 3; i++) {
8 if (num[i] == num[i + 1] && num[i + 1] == num[i + 2]) {
9 if (strncmp(&num[i], maxGood, 3) > 0) {
10 strncpy(maxGood, &num[i], 3);
11 maxGood[3] = '\0';
12 }
13 }
14 }
15 return strdup(maxGood);
16}
17
18int main() {
19 char num[] = "6777133339";
20 printf("%s\n", largestGoodInteger(num));
21 return 0;
22}
The C solution uses a for loop to traverse the string. For each substring of length 3, it checks if all characters are the same. If so, it compares it with the current maximum good integer stored in maxGood
. It updates maxGood
whenever a greater good integer is found. Finally, the largest such integer is returned.
This approach builds upon the basic iteration method, with an early termination feature if the maximum possible good integer ("999") is found. This can optimize cases where digits towards the start of the string quickly identify the upper bound, reducing unnecessary checks.
Time Complexity: Less than O(n) in the best case if "999" is early.
Space Complexity: O(1).
1#include <string>
using namespace std;
string largestGoodIntegerOptimized(string num) {
string maxGood = "";
for (int i = 0; i <= num.size() - 3; ++i) {
if (num[i] == num[i + 1] && num[i + 1] == num[i + 2]) {
if (num[i] == '9') return "999";
string curr = num.substr(i, 3);
if (curr > maxGood) {
maxGood = curr;
}
}
}
return maxGood;
}
int main() {
string num = "7779133339";
cout << largestGoodIntegerOptimized(num) << endl;
return 0;
}
In C++, the optimized approach leverages an early exit condition for the string form '999'. This substantially shortens processing time for certain inputs.