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
Solve with full IDE support and test cases
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 <stdio.h>
2#include <string.h>
3
4char* largestGoodIntegerOptimized(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 (num[i] == '9') return "999";
10 if (strncmp(&num[i], maxGood, 3) > 0) {
11 strncpy(maxGood, &num[i], 3);
12 maxGood[3] = '\0';
13 }
14 }
15 }
16 return strdup(maxGood);
17}
18
19int main() {
20 char num[] = "6779133339";
21 printf("%s\n", largestGoodIntegerOptimized(num));
22 return 0;
23}
The optimized C solution works similarly to the brute force solution but includes a check to immediately return "999" once it's encountered because it represents the maximum possible good integer.