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); } } }
Seems like cookies are disabled on this browser, please enable them to open this website
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