We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Data Structures
- Heap
- Jesse and Cookies
- Discussions
Jesse and Cookies
Jesse and Cookies
+ 0 comments Short JAVA solution, using priority-queue to optimize sorted insertions
public static int cookies(int k, List<Integer> cookies) { int result = 0; PriorityQueue<Integer> cookiesSorted = new PriorityQueue<>(cookies); while (cookiesSorted.size() >= 2 && cookiesSorted.peek() < k) { cookiesSorted.add(cookiesSorted.poll() + 2 * cookiesSorted.poll()); result++; } return cookiesSorted.peek() < k ? -1 : result; }
+ 0 comments public static int cookies(int k, List<Integer> A) { PriorityQueue<Integer> pq = new PriorityQueue<Integer>(A); int iterations = 0; while (pq.size() > 0) { Integer lowest = pq.poll(); if (lowest >= k) { return iterations; } Integer secondLowest = pq.poll(); if (secondLowest != null) { final Integer combined = lowest + (2 * secondLowest); pq.offer(combined); } else { return -1; //this will only happen if 1 item left less than k } iterations++; } return iterations; //would only get here is pq size of 0 }
+ 0 comments int cookies(int k, vector<int> A) { priority_queue<int, vector<int>, greater<int> > pq; for(int i : A)pq.push(i); int ans = 0; int temp = pq.top(); pq.pop(); while(temp < k){ if(pq.empty()) return -1; int secTemp = pq.top(); pq.pop(); pq.push(temp+2*secTemp); temp = pq.top(); pq.pop(); ans++; } return ans ; }``
+ 0 comments public static int cookies(int k, List<Integer> A) { if(A.size()<=1) return -1; A = A.stream().filter(x -> x < k).collect(Collectors.toList()); if(A.size()==0) return 0; //no operations needed if(A.size()==1) return 1; PriorityQueue<Integer> p = new PriorityQueue<>(); p.addAll(A); int operations = 0; while(p.peek() < k && p.size() >=2){ int smallest = p.remove(); int secondSmallest = p.remove(); p.add(smallest + 2*secondSmallest); ++operations; } if(p.peek()>=k) return operations; else return -1; }
+ 1 comment Can anyone tell what's wrong in this
def cookies(k, A): # Write your code here count = 0 A.sort() while(A[0]<k): if(len(A)==1): return -1 A.remove(A[0]) A.remove(A[1]) A.append(A[0]+2*A[1]) count+=1 A.sort() return count
Load more conversations
Sort 326 Discussions, By:
Please Login in order to post a comment