# 949. Largest Time for Given Digits

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LekNH5IywF8mjBxFcnu%2Fuploads%2Fybc9nLlKSyzN3GTOxsND%2F%E5%9C%96%E7%89%87.png?alt=media\&token=a30fe2a8-2027-4c30-b31d-7f858f77bafa)



![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LekNH5IywF8mjBxFcnu%2Fuploads%2F8PW9cZJwcsjF8tiJCL2L%2F%E5%9C%96%E7%89%87.png?alt=media\&token=ba3e0dbe-d739-4987-b21c-6b21492455f8)

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);
```

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LekNH5IywF8mjBxFcnu%2Fuploads%2FkT1WJ2ch9km9H0M5x0gr%2F%E5%9C%96%E7%89%87.png?alt=media\&token=de735329-caaa-4911-9823-6db9f9f51e70)



time: O(8\*4) = O(32) = O(1), worst time

space: O(1)

```java
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 ""
*/
```
