2264. Largest 3-Same-Digit Number in String (LeetCode) (solution: C++, C#)


Problem Name: 2264. Largest 3-Same-Digit Number in String
Problem Link: https://leetcode.com/problems/largest-3-same-digit-number-in-string/
Difficulty: Easy
Tag: String
Language: C# | C++
OJ: LeetCode

Algorithm:
1.Initialize an empty string answer to store the result.
2.Initialize a variable sum to -1 to keep track of the maximum sum found.
3.Iterate through the input string num from the second character (index 1) to the second-to-last character.
🏈Calculate the sum of the current three consecutive digits (characters) by converting them to integers and adding them.
🏈Check if the current three digits are equal and if the calculated sum is greater than the current maximum sum.
🏈If both conditions are true, update the answer string and sum.

4.After the iteration, answer will contain the substring with the maximum sum of integer values.
5.Return the answer string.

Code(C#)
public class Solution
{
    public string LargestGoodInteger(string num)
    {
        string answer = "";
        int sum = -1;
        for(int i=1; i<num.Length-1; i++)
        {
            int added = (num[i-1] - '0') + (num[i] - '0') + (num[i+1] - '0');
            if (num[i-1] == num[i] && num[i] == num[i+1] && sum < added)
            {
                answer = "";
                answer += num[i-1];
                answer += num[i];
                answer += num[i+1];
                sum = added;
            }
        }
        return answer;
    }
}

Code(C++)
class Solution {
public:
    string largestGoodInteger(string num) {
        string answer = "";
        int sum = -1;
        
        for (int i = 1; i < num.length() - 1; i++) {
            int added = (num[i - 1] - '0') + (num[i] - '0') + (num[i + 1] - '0');
            if (num[i - 1] == num[i] && num[i] == num[i + 1] && sum < added) {
                answer = "";
                answer += num[i - 1];
                answer += num[i];
                answer += num[i + 1];
                sum = added;
            }
        }
        
        return answer;
    }
};