The create_max
function takes an input number num
as a string and an integer k
as parameters, returning the maximum number that can be formed by removing digits from num
and keeping at most k
digits. The function uses a stack to iteratively select the largest digits from num
until a maximum number of k
digits have been chosen.
def create_max(num, k):
digits = list(num)
drop = len(digits) - k
stack = []
for digit in digits:
while drop and stack and stack[-1] < digit:
stack.pop()
drop -= 1
stack.append(digit)
return ''.join(stack[:k])
num = '912583'
assert create_max(num, 1) == '9'
assert create_max(num, 2) == '98'
assert create_max(num, 3) == '983'
assert create_max(num, 4) == '9583'
assert create_max(num, 5) == '92583'
print('All passed!')
def create_max(num: str, k: int) -> str:
"""
Returns the k largest digits from the input number, in descending order.
Args:
num (str): The input number as a string.
k (int): The number of largest digits to return.
Returns:
str: The k largest digits from the input number, in descending order.
"""
# Convert the input number to a list of digits for easier manipulation
digits = list(num)
# Calculate the number of digits to drop from the end of the list
drop = len(digits) - k
# Initialize an empty stack to store the digits
stack = []
# Iterate over each digit in the list
for digit in digits:
# While there are digits to drop from the stack and the top of the stack is less than the current digit
while drop and stack and stack[-1] < digit:
# Remove the top digit from the stack
stack.pop()
# Decrement the number of digits to drop
drop -= 1
# Push the current digit onto the stack
stack.append(digit)
# Return the k largest digits from the stack as a string
return ''.join(stack[:k])
# Test cases
num = '912583'
assert create_max(num, 1) == '9'
assert create_max(num, 2) == '98'
assert create_max(num, 3) == '983'
assert create_max(num, 4) == '9583'
assert create_max(num, 5) == '92583'
print('All passed!')
create_max
num
: the input number as a stringk
: the number of digits to be keptThe function create_max
returns the maximum number that can be formed by removing digits from the input number num
and keeping at most k
digits.
num
to a list of digits.drop
is greater than 0):
drop
by 1.k
digits from the stack.The code includes several assertions to test the function with different inputs and expected outputs. The function is then called with the input number '912583'
and k
values from 1 to 5, and the results are printed.