Перейти к содержимому

LeetCode Daily #3723: 14 Oct 2026 | Maximize Sum of Squares of Digits, Greedy Nines First

Brute To Best

0:00 / 0:00

LeetCode Daily #3723: 14 Oct 2026 | Maximize Sum of Squares of Digits, Greedy Nines First

35 просмотров · 2 недели назад
Brute To Best
101 подписчик
35 просмотров · 2 недели назад
Brute to Best: every LeetCode problem, from the naive solution to the optimal one. In this video: The problem: you get two positive integers, num and sum. A good integer has exactly num digits, and its digits add up to exactly sum. Its score is the sum of the squares of its digits. Return the good integer with the highest score. If several tie, return the largest one. If none exists, return an empty string. Brute force: try every num-digit number, keep the ones whose digits add up to sum, and score each one. That is exponential in num. The key insight: with the digit sum fixed, putting as much of it as possible into big digits gives the largest sum of squares. For a sum of 10, 9, 1, 0 scores 82, while 3, 3, 4 only scores 34. Feasibility: num digits can add up to at most 9 × num. If sum is greater than that, return an empty string. Build the answer: write sum ÷ 9 nines, then the leftover sum % 9 if it isn't 0, then zeros until there are num digits. Putting the biggest digits first also makes it the largest number among the ties. Dry run with num = 4 and sum = 20: two 9s, then a 2, then a 0, which gives 9920 with a score of 81 + 81 + 4 = 166. Complexity: O(num) time and O(num) space for the output string. Problem: https://leetcode.com/problems/maximiz... Related: Largest Number (179), Maximum Swap (670), Monotone Increasing Digits (738) Full Brute to Best playlist on the channel. Subscribe for a new LeetCode problem, solved from brute force to the best solution, every day. Hashtags #leetcode #leetcodedaily #leetcode3723 #maximizesumofsquaresofdigits #greedy #math #digits #string #medium #coding #codinginterview #dsa #python #google #brutetobest