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 <= 100number consists of digits from '1' to '9'.digit is a digit from '1' to '9'.digit occurs at least once in number.Iterate through the string and check each occurrence of the given digit. For each occurrence, remove it to form a new number. Compare each of these new numbers and return the largest one.
This Python solution iterates over each character in the string 'number'. When it finds the specified 'digit', it creates a new string by excluding that particular digit from 'number'. Each new string is compared to the previously recorded maximum value. After the loop, the maximum string found is returned.
C++
Java
C
C#
JavaScript
Time Complexity: O(n), where n is the length of 'number'.
Space Complexity: O(1), as only a few variables are used regardless of the input size.
Remove K Digits - Leetcode 402 - Python • NeetCode • 68,668 views views
Watch 9 more video solutions →Practice Remove Digit From Number to Maximize Result with our built-in code editor and test cases.
Practice on FleetCode