| 1 | class Solution { |
| 2 | public String longestDiverseString(int a, int b, int c) { |
| 3 | // create a pq (decreasing order of element count) |
| 4 | PriorityQueue<Pair> pq = new PriorityQueue<>(); |
| 5 | if(a>0){ |
| 6 | pq.offer(new Pair(a,'a')); |
| 7 | } |
| 8 | if(b>0){ |
| 9 | pq.offer(new Pair(b,'b')); |
| 10 | } |
| 11 | if(c>0){ |
| 12 | pq.offer(new Pair(c,'c')); |
| 13 | } |
| 14 | |
| 15 | StringBuilder res = new StringBuilder(); |
| 16 | while(!pq.isEmpty()){ |
| 17 | Pair node = pq.poll(); |
| 18 | int n = res.length(); |
| 19 | char ch = node.ch; |
| 20 | int count = node.count; |
| 21 | // if current element is same as last two then push the second highest freq |
| 22 | // element |
| 23 | if(n>=2 && res.charAt(n-1) == ch && res.charAt(n-2) == ch) { |
| 24 | // if sec highest freq element is not present then break |
| 25 | if(pq.isEmpty()) break; |
| 26 | Pair sec = pq.poll(); |
| 27 | res.append(sec.ch); |
| 28 | sec.count--; |
| 29 | if(sec.count>0){ |
| 30 | pq.offer(new Pair(sec.count,sec.ch)); |
| 31 | } |
| 32 | }else{ |
| 33 | res.append(node.ch); |
| 34 | node.count--; |
| 35 | } |
| 36 | // if element count is not 0, insert in pq with updated count |
| 37 | if(node.count>0){ |
| 38 | pq.offer(new Pair(node.count,node.ch)); |
| 39 | } |
| 40 | } |
| 41 | return res.toString(); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | |
| 46 | class Pair implements Comparable<Pair> { |
nothing calls this directly
no outgoing calls
no test coverage detected