Sponsored
Sponsored
To form the maximum odd binary number from a given binary string, observe that the binary number should have '1' at the end to be odd. Among the remaining bits, arrange as many '1's as possible at the leading positions while maintaining the '1' at the end. This approach involves counting the occurrences of '1' and '0', then constructing the number.
Time Complexity: O(n), where n is the length of the string as it needs one pass to count and another to construct.
Space Complexity: O(1) for the counting variables.
The program first counts the '1's and '0's. It reserves one '1' for the end to make the number odd. The rest of the '1's are placed at the beginning, and '0's fill the remaining positions before the final '1'.
A different approach involves sorting the binary string while ensuring a '1' is at the end. To maximize the binary number, the initial part of the string should consist of leading '1's followed by '0's, then append a single '1' at the end to turn the number odd.
Time Complexity: O(n log n) for sorting.
Space Complexity: O(1) assuming sorting in place is allowed.
1import java.util.Arrays;
2
3public class MaxOddBinaryNumber {
4 public static String maxOddBinary(String s) {
5 char[] arr = s.toCharArray();
6 Arrays.sort(arr);
7 int last_one_index = s.lastIndexOf('1');
8 char temp = arr[arr.length - 1];
9 arr[arr.length - 1] = arr[last_one_index];
10 arr[last_one_index] = temp;
11 return new String(arr);
12 }
13
14 public static void main(String[] args) {
15 String s = "0101";
16 System.out.println(maxOddBinary(s));
17 }
18}Java's Arrays.sort used here ensures proper arrangement; swapping ensures legality where '1' must end the string.
Solve with full IDE support and test cases