You are viewing a single comment's thread. Return to all comments →

a heap can be used to implement a priority que and thus they are synonymos.

A[0] remains empty A[1] is the heap head (max or min your choice) and for A[k] the left node is at A[2k] and the right at A[2k + 1]

here is my solution using a PriorityQueue

public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int operations = 0; PriorityQueue<Integer> que = new PriorityQueue<Integer>(); for(int i = 0; i < n; i++) { que.add(sc.nextInt()); } while(que.size() > 1 && que.peek() < k) { int leastSweet = que.poll(); int secondLeast = que.poll(); que.add(leastSweet + 2*secondLeast); operations++; } if(que.peek() < k) { System.out.print(-1); } else { System.out.print(operations); } } }

My solution is exactly like this, but 2 cases are failing because of timeout. How did you resolve it?

Check your while should contain both conditions while (queue.size() > 1 && queue.peek() < K) because while (queue.peek() < K) won't suffice.

you might be lucky...my two test cases are also failing due to TLE.

## Jesse and Cookies

You are viewing a single comment's thread. Return to all comments →

a heap can be used to implement a priority que and thus they are synonymos.

A[0] remains empty A[1] is the heap head (max or min your choice) and for A[k] the left node is at A[2k] and the right at A[2k + 1]

here is my solution using a PriorityQueue

My solution is exactly like this, but 2 cases are failing because of timeout. How did you resolve it?

Check your while should contain both conditions while (queue.size() > 1 && queue.peek() < K) because while (queue.peek() < K) won't suffice.

you might be lucky...my two test cases are also failing due to TLE.