-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC1405.java
More file actions
87 lines (73 loc) · 2.23 KB
/
LC1405.java
File metadata and controls
87 lines (73 loc) · 2.23 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
* LC1405
*/
import java.util.*;
class Pair implements Comparable<Pair> {
int count;
char ch;
Pair(int count, char ch) {
this.count = count;
this.ch = ch;
}
public int compareTo(Pair that) { // return the decreasing order of count
return that.count - this.count;
}
}
public class LC1405 {
public static String longestDiverseString(int a, int b, int c) {
// create a pq (decreasing order of element count)
PriorityQueue<Pair> pq = new PriorityQueue<>();
if (a > 0) {
pq.offer(new Pair(a, 'a'));
}
if (b > 0) {
pq.offer(new Pair(b, 'b'));
}
if (c > 0) {
pq.offer(new Pair(c, 'c'));
}
StringBuilder res = new StringBuilder();
while (!pq.isEmpty()) {
Pair node = pq.poll();
int n = res.length();
char ch = node.ch;
int count = node.count;
// if current element is same as last two then push the second highest freq
// element
if (n >= 2 && res.charAt(n - 1) == ch && res.charAt(n - 2) == ch) {
if (pq.isEmpty()) {
break;
}
Pair sec = pq.poll();
res.append(sec.ch);
sec.count--;
if (sec.count > 0) {
pq.offer(new Pair(sec.count, sec.ch));
}
} else {
res.append(node.ch);
node.count--;
}
// if element count is not 0, insert in pq with update count
if (node.count > 0) {
pq.offer(new Pair(node.count, node.ch));
}
}
return res.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter A : ");
int a = sc.nextInt();
System.out.println();
System.out.print("Enter B : ");
int b = sc.nextInt();
System.out.println();
System.out.print("Enter C : ");
int c = sc.nextInt();
System.out.println();
String ans = longestDiverseString(a, b, c);
System.out.println(ans);
sc.close();
}
}