Talentd
FleetCode

4000. Largest Integer With Given Digit Sum

Easy61.6% acceptance

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 <= 5
  • 0 <= s <= 100

Hints open one at a time

Hint 1

1a (Brute Force). Since n <= 5, there are at most 105 non-negative integers with at most n digits.

Hint 2

1b (Brute Force). Check every integer from 0 to 10n - 1, and keep the largest one whose digit sum is s.

Hint 3

2a (Greedy). If s > 9 * n, no valid integer exists.

Hint 4

2b (Greedy). To maximize the integer, assign as much of the remaining digit sum as possible to each digit from left to right.

Hint 5

2c (Greedy). Handle s == 0 separately: the answer is 0.

16:22
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def largestInteger(self, n: int, s: int) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
2
9
Input
2
19
Input
5
0
Your code is saved on this device.Solution