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.
1function largestGoodInteger(num) {
2 let maxGood = "";
3 for (let i = 0; i <= num.length - 3; i++) {
4 if (num[i] === num[i+1] && num[i+1] === num[i+2]) {
5 let curr = num.substring(i, i + 3);
6 if (curr > maxGood) {
7 maxGood = curr;
8 }
9 }
10 }
11 return maxGood;
12}
13
14console.log(largestGoodInteger("6777133339"));
JavaScript utilizes similar logic with localized variables and checks for identifying and updating the largest good integer found by examining each triplet and comparing lexically.
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.