我想从给定的4位数中找到最大有效时间。我已经使用数字(2,4,0,0)。该代码返回20:42而它应该返回20:40。 有关如何解决此问题的任何建议?4位数的最大有效时间
import java.util.ArrayList;
import java.util.List;
public class MaxTimeCombination {
public static void main(String[] args) {
System.out.println(solution(2, 4, 0, 0));
System.out.println(solution(3, 0, 7, 0));
}
public static String solution(int A, int B, int C, int D) {
// brute force permutation
int[] temp = new int[] {A, B, C, D};
List<List<Integer>> permutation = permute(temp);
int h = Integer.MIN_VALUE;
int m = Integer.MIN_VALUE;
boolean exists = false;
/* System.out.println("Permutations:" + permutation);
for (int i = 0; i < permutation.size(); i++) {
if (permutation.get(i).get(0) > 0 && permutation.get(i).get(0) < 3){
List <Integer> output = permutation.get(i);
System.out.println(output);
}
}*/
for (int i = 0; i < permutation.size(); i++) {
//if (permutation.get(i).get(0) > 0 && permutation.get(i).get(0) < 3){
List<Integer> k = permutation.get(i);
//System.out.println("Sorted :" + k);
int hh = k.get(0)*10 + k.get(1);
if (hh < 24) {
exists = true;
if (hh > h) {
h = hh;
}
}
int mm = k.get(2)*10 + k.get(3);
if (mm < 60) {
exists = true;
if (mm > m) {
m = mm;
}
}
}
return (exists ? String.format("%02d:%02d", h, m) : "NOT POSSIBLE");
}
public static List<List<Integer>> permute(int[] num) {
List<List<Integer>> result = new ArrayList<>();
//start from an empty list
result.add(new ArrayList<>());
for (int i = 0; i < num.length; i++) {
//list of list in current iteration of the array num
List<List<Integer>> current = new ArrayList<>();
for (List<Integer> l : result) {
// # of locations to insert is largest index + 1
for (int j = 0; j < l.size()+1; j++) {
// + add num[i] to different locations
l.add(j, num[i]);
List<Integer> temp = new ArrayList<>(l);
current.add(temp);
//System.out.print(temp + " ");
//l.remove(num[i]);
l.remove(j);
}
}
result = new ArrayList<>(current);
}
return result;
}
}
它似乎它正在返回正确的答案可以请详细说明如何最大有效20:40而不是20:42:/ –
我猜是因为第四次输入数字将不会被使用然后@ZainUlAbidin。如果你不想让2,再次出现,你可以在使用一次后将其列入黑名单。 – Nico
因为您知道输出格式,只需要4位数字。那么,为什么你不把输入结合到4位数的整数中=>具有2个第一个数字<= 23的过滤器最大整数,其余部分为<= 59 =>格式化为时间。 –