-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path949-largest-time-for-given-digits
52 lines (38 loc) · 1.07 KB
/
949-largest-time-for-given-digits
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
private int max = -1;
public String largestTimeFromDigits(int[] A) {
dfs(A,0);
if(max ==-1){
return "";
}else{
return String.format("%02d:%02d",max/100,max%100);
}
}
private void dfs(int[]A, int start){
if(start==A.length){
this.getMaxTime(A);
return;
}
//recurse
for(int i=start; i<A.length; i++){
this.swap(A,i,start);
this.dfs(A,start+1);
this.swap(A,i,start);
}
}
private void getMaxTime(int[] A){
int hour = A[0]*10 + A[1];
int mins = A[2]*10 + A[3];
if(hour<24 && mins <60) {
//time is valid. check if current time is higher than prev highest
max = Math.max(max, hour*100+mins);
}
}
private void swap(int[] A, int x, int y){
if(x!=y){
int temp = A[x];
A[x] = A[y];
A[y] = temp;
}
}
}