Untitled
unknown
java
a year ago
1.8 kB
7
Indexable
import java.util.*;
public class Solution {
public static int solution(int[] digits) {
// Find the top three maximum numbers by a single pass
int max1 = -1, max2 = -1, max3 = -1;
for (int num : digits) {
if (num > max1) {
max3 = max2;
max2 = max1;
max1 = num;
} else if (num > max2) {
max3 = max2;
max2 = num;
} else if (num > max3) {
max3 = num;
}
}
// Now we need to combine these three numbers in the best possible way
// Since the problem states using at most three digits, we consider 1, 2, or 3 of them
int result = max1; // Best single digit
if (max2 != -1) { // Check if we have a second digit
result = Math.max(result, 10 * max1 + max2);
result = Math.max(result, 10 * max2 + max1);
}
if (max3 != -1) { // Check if we have a third digit
result = Math.max(result, 100 * max1 + 10 * max2 + max3);
result = Math.max(result, 100 * max1 + 10 * max3 + max2);
result = Math.max(result, 100 * max2 + 10 * max1 + max3);
result = Math.max(result, 100 * max2 + 10 * max3 + max1);
result = Math.max(result, 100 * max3 + 10 * max1 + max2);
result = Math.max(result, 100 * max3 + 10 * max2 + max1);
}
return result;
}
public static void main(String[] args) {
int[] digits1 = {7, 2, 3, 3, 4, 9};
int[] digits2 = {0, 0, 5, 7};
System.out.println(solution(digits1)); // Should return 974
System.out.println(solution(digits2)); // Should return 75
}
}
Editor is loading...
Leave a Comment