You are given a string num representing a large integer. A good integer is one that has an even number of digits and the number of 3-same-digit numbers in it is maximized.
No, wait - let me read the problem again:
Actually, you are given a string num representing a large integer. Return the largest good integer as a string, where a good integer is a substring of exactly 3 identical digits.
More precisely: Return the maximum 3-digit number (as a string) where all three digits are the same. If no such number exists, return an empty string.
A 3-digit number abc where a == b == c and a, b, c are digits.
3 <= num.length <= 1000num consists only of digitsIterate through the string and check every three consecutive characters to see if they form a 3-same-digit number.
Algorithm:
Example Input: num = "6777133339"
Step-by-step execution:
Maximum value = 777, return “777”
class Solution {
    public String largestGoodInteger(String num) {
        long max = Long.MIN_VALUE;
        for (int i = 0; i < num.length() - 2; i++) {
            if (num.charAt(i) == num.charAt(i + 1) &&
                num.charAt(i + 1) == num.charAt(i + 2)) {
                long val = Long.parseLong(num.substring(i, i + 3));
                if (val > max) max = val;
            }
        }
        if (max == 0) return "000";
        return max > Long.MIN_VALUE ? String.valueOf(max) : "";
    }
}
Use a counter to track consecutive identical digits instead of parsing substrings.
Algorithm:
Example Input: num = "6777133339"
Step-by-step execution:
Maximum digit = ‘7’, return “777”
class Solution {
    public String largestGoodInteger(String num) {
        int count = 0;
        char max = ' ';
        char prev = ' ';
        for (char ch : num.toCharArray()) {
            if (ch == prev) count++;
            else count = 1;
            if (count == 3) {
                max = (char) Math.max(max, ch);
            }
            prev = ch;
        }
        return max == ' ' ? "" : String.valueOf(max).repeat(3);
    }
}
Pre-store all possible 3-same-digit numbers and check which one exists in the string.
Algorithm:
Example Input: num = "6777133339"
Predefined candidates: [“999”, “888”, “777”, “666”, “555”, “444”, “333”, “222”, “111”, “000”]
Step-by-step execution:
Return “777” immediately
class Solution {
    public String largestGoodInteger(String num) {
        String[] candidates = { "999", "888", "777", "666", "555",
                                 "444", "333", "222", "111", "000" };
        for (String c : candidates) {
            if (num.contains(c)) return c;
        }
        return "";
    }
}
| Approach | Time Complexity | Space Complexity | Readability | Performance | 
|---|---|---|---|---|
| Approach 1 | O(n) | O(1) | Medium | Good | 
| Approach 2 | O(n) | O(1) | High | Best | 
| Approach 3 | O(n) | O(1) | High | Best | 
Recommendation: Approach 2 is the most efficient and readable solution for this problem.