Largest Integer With Given Digit Sum Problem
#4000
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 4000.
You are given two non-negative integers n and s.
Return the largest integer that has at most n digits and whose sum of digits is s. If no such integer exists, return -1.
Example 1:
Input: n = 2, s = 9
Output: 90
Explanation:
The largest integer with at most 2 digits that has a sum of digits of 9 is 90.
Example 2:
Input: n = 2, s = 19
Output: -1
Explanation:
There is no integer with at most 2 digits that has a sum of digits of 19, so the answer is -1.
Example 3:
Input: n = 5, s = 0
Output: 0
Explanation:
The only non-negative integer whose digits sum to 0 is 0.
Constraints:
1 <= n <= 50 <= s <= 100
Solution
Approach: Greedy
If n * 9 < s, even n nines cannot reach the digit sum s, so return -1.
Otherwise make the number as large as possible by giving the highest places the largest digits. Build the n digits from left to right: each digit is min(s, 9), and we subtract it from s. Once s reaches 0 the remaining digits are zeros, and a leading 0 just means the number has fewer than n digits. For s = 0 the answer is 0.
Complexity: time O(n), space O(1).
class Solution:
def largestInteger(self, n: int, s: int) -> int:
if n * 9 < s:
return -1
ans = 0
for _ in range(n):
x = min(s, 9)
ans = ans * 10 + x
s -= x
return ans