Max Avg Number

Find the maximum of a number, such that every adjacent pair of numbers of averaged throughout its sequence.

e.g.

623315 -> 62333


"" + avg(6,2) + 3315 = max(0,43315)
6  + avg(2,3) + 315 = max(43315,62315)

...
int max_avg(int number)
{
    string str_num = to_string(number);

    string left, avg, right;
    int new_max = 0;
    int new_num = 0;

    int count = 0;
    for (int i = 1; i < str_num.length(); i++)
    {
        avg = to_string(((str_num[i - 1] - '0') + (str_num[i] - '0')) / 2);
        left = str_num.substr(0, count++);
        right = str_num.substr(i + 1, str_num.length() - count);
        new_num = stoi((left + avg + right).c_str());
        new_max = max(new_num, new_max);
    }

    return new_max;
}

int main() 
{
    cout << max_avg(623315) << endl;
}

Last updated