Contents

Make a big number (with.Java)

   Aug 15, 2024     2 min read

This is an article about the problem of making large numbers (with.Java).

I would like to solve the coding test problem and reflect on the problem I solved.

Let’s get to the problem first.

Problem

You want to find the largest number you can get when you remove k from a number.

For example, if you remove two numbers from the number 1924, you can create [19, 12, 14, 92, 94, 24].

The largest number of these is 94.

The number of numbers and the number k to be removed in string format are given as parameters of the solution function.

Complete the solution function so that when you remove k numbers from the number, you return the largest number you can create in the form of a string.

Restrictions

  • Number is a number greater than or equal to 2 digits and less than 1,000,000 digits.
  • k is a natural number greater than or equal to one number and less than one digit.

Input/Output Examples

numberkreturn
β€œ1924”2β€œ94”
β€œ1231234”3β€œ3234”
β€œ4177252841”4β€œ775841”

my solution to the problem

class Solution {
    public String solution(String number, int k) {
        String answer = "";
        StringBuilder sb = new StringBuilder();
        int idx = 0;
        int num;
        for(int i = 0; i < number.length() - k; i++){
            num = 0;
            for(int j = idx; j <= k + i; j++){
                if(num < number.charAt(j) - '0'){
                    num = number.charAt(j) - '0';
                    idx = j + 1;
                }
            }
            sb.append(num);
        }
        return sb.toString();
    }
}

Solution Description

  • Use StringBuilder sb to save the results.
  • The idx variable represents the index of the number selected so far.
  • The num variable stores the largest number of the selected numbers.
  • The outer iteration repeats until the resulting string is number.length() -k.
  • The inner iteration selects the largest number among the remaining numbers, excluding the number selected so far.
  • Adds the largest number selected to the result.

Conclusion

This code solves the problem using the Greedy method.

The Greedy method is an algorithm that makes the best choice right now at each stage and consequently finds the optimal solution.