Insert 5 to Make Number Largest in Python

Given a number n, we need to find the maximum number we can create by inserting the digit '5' at any position in the number. This problem involves string manipulation and finding the optimal position to maximize the resulting number.

So, if the input is like n = 826, then the output will be 8526 (inserting '5' after the first digit creates the largest possible number).

Algorithm Steps

To solve this problem, we follow these steps ?

  • Convert the number n to a string for easy manipulation
  • Initialize ans to negative infinity to track the maximum result
  • Try inserting '5' at every possible position (0 to length of string)
  • For each position, create a candidate number by concatenating substrings
  • Skip the first position if the number is negative (starts with '-')
  • Keep track of the maximum value among all candidates
  • Return the maximum result

Example Implementation

Here's the complete implementation of the solution ?

class Solution:
    def solve(self, n):
        temp = str(n)
        ans = float('-inf')
        
        for i in range(len(temp) + 1):
            cand = temp[:i] + '5' + temp[i:]
            if i == 0 and temp[0] == '-':
                continue
            ans = max(ans, int(cand))
        
        return ans

# Test the solution
ob = Solution()
print(ob.solve(826))
print(ob.solve(123))
print(ob.solve(999))
8526
5123
9995

How It Works

The algorithm works by trying all possible insertion positions:

  • For 826: positions give us 5826, 8526, 8256, 8265
  • The maximum among these is 8526
  • For positive numbers, we want to insert '5' as early as possible where it creates the largest digit at that position

Alternative Optimized Approach

We can optimize this by finding the first position where the current digit is smaller than 5 ?

def insert_five_optimized(n):
    s = str(n)
    
    # Handle negative numbers
    if s[0] == '-':
        # For negative numbers, find first digit > 5 from left
        for i in range(1, len(s)):
            if s[i] > '5':
                return int(s[:i] + '5' + s[i:])
        return int(s + '5')  # Append if no digit > 5 found
    
    # For positive numbers, find first digit < 5 from left
    for i in range(len(s)):
        if s[i] < '5':
            return int(s[:i] + '5' + s[i:])
    
    # If all digits >= 5, append at the end
    return int(s + '5')

# Test the optimized solution
print(insert_five_optimized(826))
print(insert_five_optimized(123))
print(insert_five_optimized(-826))
8526
5123
-8256

Conclusion

The brute force approach tries all positions and finds the maximum, while the optimized version directly finds the best insertion position. Both methods effectively solve the problem of inserting '5' to create the largest possible number.

Updated on: 2026-03-25T10:24:08+05:30

575 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements