Sort by

recency

|

360 Discussions

|

  • + 1 comment
    # using heap sort
    import heapq
    def cookies(k, nums):
        # Write your code here
        heapq.heapify(nums)
        count =0
        
        while(nums):
            x = heapq.heappop(nums)
            if x>=k:
                return count
            
            if not nums:
                return -1
            y = heapq.heappop(nums)
            
            #formula
            n = x + (2*y)
            heapq.heappush(nums, n)
            count+=1
            
        # loop exits without giving count
        return -1
    
  • + 0 comments

    The example might have an error after [16,8,7,6], the next iteration should return a smaller array i.e. [20,16,8], but it still includes the 7 which should've been extracted.

  • + 0 comments
    import java.io.*;
    import java.util.*;
    import java.text.*;
    import java.math.*;
    import java.util.regex.*;
    
    public class Solution {
    
        public static void main(String[] args) {
        
            Scanner scan=new Scanner(System.in);
            int n=scan.nextInt();
            int k=scan.nextInt();
            PriorityQueue<Integer> queue=new PriorityQueue<Integer>();
            for(int i=0;i<n;i++)
                {
                queue.add(scan.nextInt());
            }
            int count=0;
            while(queue.peek()<k)
                {
                if(queue.size()>=2)
                    {
                int x=queue.remove();
                int y=queue.remove();
                y=x+2*y;
                queue.add(y);
                count++;
                }
                else
                    {
                    count=-1;
                    break;
                }
            }
            System.out.println(count);
        }
    }
    
  • + 0 comments
    int cookies(int k, vector<int> arr) {
        priority_queue<int, vector<int>, greater<int>> pq(arr.begin(), arr.end());
        int count = 0;
    
        while (pq.size() > 1 && pq.top() < k)
        {
            int first = pq.top();
            pq.pop();
            int second = pq.top();
            pq.pop();
    
            pq.push(first + 2 * second);
            count++;
        }
        return (pq.top() >= k) ? count : -1;   
    }
    
  • + 1 comment

    Here is my solution. It uses python heapq library. It is fast

    def cookies(k, A):
        import heapq
    
        heapq.heapify(A)
        count = 0
        while not all(i >= k for i in A): # until all cookies are >= k
            if len(A) == 1:
                return -1
            a, b = heapq.heappop(A), heapq.heappop(A)
            c = a + 2 * b
            heapq.heappush(A, c)
            count += 1
        return count