#3723
Maximize Sum of Squares of Digits
MediumMathGreedyGreedyArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use a greedy approach to fill the digits from left to right with the highest possible values (9s) while ensuring the total digit sum equals 'sum'.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an array of size 'num' with zeros.
- 2Step 2: Fill the array from left to right with 9s until the remaining sum is less than 9.
- 3Step 3: Place the remaining sum in the next position and convert the array to a string.
solution.py12 lines
1def maxSumOfSquares(num, sum):
2 if sum > 9 * num or sum == 0 and num > 1:
3 return ''
4 digits = [0] * num
5 for i in range(num):
6 if sum > 9:
7 digits[i] = 9
8 sum -= 9
9 else:
10 digits[i] = sum
11 break
12 return ''.join(map(str, digits))ℹ
Complexity note: The algorithm runs in linear time as we iterate through the digits once.
- 1Maximize leftmost digits for higher scores
- 2Sum of digits must equal 'sum'
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.