still need this , when [2,0, 6, 6], the first one cant get right ans, should consider another case start from 1
res = res ||
findMaxAndRearrange(0, 1, arr) &&
findMaxAndRearrange(1, 9, arr) &&
findMaxAndRearrange(2, 5, arr) &&
findMaxAndRearrange(3, 9, arr);
class Solution {
public String largestTimeFromDigits(int[] arr) {
boolean res =
findMaxAndRearrange(0, 2, arr) &&
(arr[0] == 2 ? findMaxAndRearrange(1, 3, arr) : findMaxAndRearrange(1, 9, arr)) &&
findMaxAndRearrange(2, 5, arr) &&
findMaxAndRearrange(3, 9, arr);
res = res ||
findMaxAndRearrange(0, 1, arr) &&
findMaxAndRearrange(1, 9, arr) &&
findMaxAndRearrange(2, 5, arr) &&
findMaxAndRearrange(3, 9, arr);
if (!res) {
return "";
}
StringBuilder sb = new StringBuilder();
return sb.append(arr[0])
.append(arr[1])
.append(":")
.append(arr[2])
.append(arr[3]).toString();
}
private boolean findMaxAndRearrange(int index, int upper, int[] arr) {
int maxIndex = -1;
for (int i = index; i < arr.length; i++) {
if (arr[i] <= upper && (maxIndex == -1 || arr[maxIndex] < arr[i])) {
maxIndex = i;
}
}
if (maxIndex == -1) {
return false;
}
int temp = arr[maxIndex];
arr[maxIndex] = arr[index];
arr[index] = temp;
return true;
}
}
/*
[1,2,3,4]
rule
23 59
??:??
__:__
19:59 1-case
23:59 2-case
if 2 in array
use in first, then 1
then if no 0, return ""
*/