[LeetCode] Maximize Sum of Squares of Digits

3723. Maximize Sum of Squares of Digits

You are given two positive integers num and sum.

A positive integer n is good if it satisfies both of the following:

  • The number of digits in n is exactly num.
  • The sum of digits in n is exactly sum.

The score of a good integer n is the sum of the squares of digits in n.

Return a string denoting the good integer n that achieves the maximum score. If there are multiple possible integers, return the maximum one. If no such integer exists, return an empty string.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
string maxSumOfSquares(int num, int sum) {
if(num * 9 < sum) return "";
string res = "";
for(int i = 0; i < num; i++) {
int now = min(sum, 9);
res.push_back(now + '0');
sum -= now;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/10/28/PS/LeetCode/maximize-sum-of-squares-of-digits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.