Skip to content

Commit

Permalink
Merge pull request #89 from prateek168/day16-java
Browse files Browse the repository at this point in the history
day 16 solution in java
  • Loading branch information
arya2004 authored Oct 19, 2024
2 parents 5e8f539 + 762dfbd commit 3176b6e
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions solutions/day16/solution_java.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import java.util.PriorityQueue;

class Solution {
public String longestDiverseString(int a, int b, int c) {
// Priority queue to store the characters and their counts.
PriorityQueue<int[]> pq = new PriorityQueue<>((x, y) -> y[0] - x[0]);
if (a > 0) pq.offer(new int[]{a, 'a'});
if (b > 0) pq.offer(new int[]{b, 'b'});
if (c > 0) pq.offer(new int[]{c, 'c'});

StringBuilder result = new StringBuilder();

while (!pq.isEmpty()) {
int[] first = pq.poll();

// Check if last two characters are the same.
if (result.length() >= 2 && result.charAt(result.length() - 1) == first[1] &&
result.charAt(result.length() - 2) == first[1]) {

if (pq.isEmpty()) break; // No more valid characters.

// Pick the second character.
int[] second = pq.poll();
result.append((char) second[1]);
second[0]--;

if (second[0] > 0) pq.offer(second);
pq.offer(first);
} else {
result.append((char) first[1]);
first[0]--;

if (first[0] > 0) pq.offer(first);
}
}

return result.toString();
}
}

0 comments on commit 3176b6e

Please sign in to comment.