Task 1: Make it Bigger
"Delete to Dominate: Maximise by Removing One!"
Given a string number and a digit character, we must remove exactly one occurrence of that digit to make the resulting decimal number as large as possible.
The Strategy: Scan from left to right for the first occurrence of the target digit where the next digit is greater. Removing that occurrence lets a bigger digit move into a higher place value. If no digit is followed by a larger one, remove the rightmost occurrence.
Perl Implementation
sub make_it_bigger {
my ($number, $digit) = @_;
my @chars = split //, $number;
my $last_idx = -1;
for my $i (0 .. $#chars) {
if ($chars[$i] eq $digit) {
$last_idx = $i;
if ($i < $#chars && $chars[$i + 1] gt $digit) {
splice @chars, $i, 1;
return join '', @chars;
}
}
}
splice @chars, $last_idx, 1 if $last_idx >= 0;
return join '', @chars;
}
Python Implementation
def make_it_bigger(number: str, digit: str) -> str:
"""
Remove exactly one occurrence of *digit* from *number* to maximise
the resulting decimal value.
"""
last_idx = -1
chars = list(number)
for i, ch in enumerate(chars):
if ch == digit:
last_idx = i
if i + 1 < len(chars) and chars[i + 1] > digit:
del chars[i]
return ''.join(chars)
if last_idx >= 0:
del chars[last_idx]
return ''.join(chars)