Saturday, November 4, 2023

 

Remove Digit From Number to Maximize Result

You are given a string number representing a positive integer and a character digit.

Return the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit occurs at least once in number.

 

Example 1:

Input: number = "123", digit = "3"

Output: "12"

Explanation: There is only one '3' in "123". After removing '3', the result is "12".

Example 2:

Input: number = "1231", digit = "1"

Output: "231"

Explanation: We can remove the first '1' to get "231" or remove the second '1' to get "123".

Since 231 > 123, we return "231".

Example 3:

Input: number = "551", digit = "5"

Output: "51"

Explanation: We can remove either the first or second '5' from "551".

Both result in the string "51".

 

Constraints:

·        2 <= number.length <= 100

·        number consists of digits from '1' to '9'.

·        digit is a digit from '1' to '9'.

·        digit occurs at least once in number.

Solution:

import java.util.*;

import java.util.Comparator;

import java.lang.*;

import java.io.*;

 

class Program

{

public static void main (String[] args) throws java.lang.Exception

{

getMaxWithOneDigitRemoval("123", "3          ");

getMaxWithOneDigitRemoval("1231", "1");

getMaxWithOneDigitRemoval("551", "5");

}

private static String getMaxWithOneDigitRemoval(Strint input, Character digit)

{

if (input == null || input.length() == 0 || digit == null) return input;

List<Integer> locations = new ArrayList<Integer>();

for (int i = 0; i < input.Length(); i++)

{

if (digit.equals(input.charAt(i)))

{

locations.add(i);

}

}

 

List<Integer> candidates = new ArrayList<Integer>();

locations.forEach(x => candidates.add(convertTo(maximize(input, x))));

return String.valueOf(candidates.stream().max(Integer::compare).get());

}

private static String maximize(String input, Integer index)

{

if (index == 0 ) return input.substring(1, input.length());

if (index == input.length() - 1) return input.substring(0, input.length() - 1);

return input.substring(0,index) + input.substring(index+1, input.length());

}

private static Integer convertTo(String input) {

int power = 0;

Integer sum = 0;

for (int i = input.length()-1; i>=0; i--)

{

sum += Integer.parseInt(input.charAt(i).toString()) * Math.pow(10, power);

power++;

}

return sum;

}

}

No comments:

Post a Comment