Jesse and Cookies

Sort by

recency

|

183 Discussions

|

  • + 0 comments
    import heapq
    def cookies(k, A):
        heapq.heapify(A)
        ways =0
        
        while len(A) > 1 and A[0] < k :
            a = heapq.heappop(A) 
            b = heapq.heappop(A) *2
            heapq.heappush(A, (a+b))
            ways +=1
    
    				
            
        if A[0] < k:
            return -1
        return ways
    
  • + 0 comments

    Python Solution with using Heap directly,

    def getElement(arr, arr2, i, j): if (len(arr) > i and len(arr2) > j): if (arr[i] <= arr2[j]): return arr[i], i+1, j else: return arr2[j], i, j+1 elif (len(arr) > i): return arr[i], i+1, j elif (len(arr2) > j): return arr2[j], i, j+1 return 0, i, j

    def cookies(k, A): arr = sorted(A) arr2 = [] i, j, ln = 0, 0, len(arr)

    if (ln == 0 and k > 0):
        return -1
    count = 0
    
    if (ln > 0):
        while((i + j + 1 < len(arr) + len(arr2)) and ((len(arr) > i and arr[i] < k) or (len(arr2) > j and arr2[j] < k))):
            count += 1
            firstSmallest, i, j = getElement(arr, arr2, i, j)
            secondSmallest, i, j = getElement(arr, arr2, i, j)
            newCookie = firstSmallest + (2 * secondSmallest)
            arr2.append(newCookie)
        if ((len(arr) > i and arr[i] < k) or (len(arr2) > j and arr2[j] < k)):
            count = -1
    return count
    
  • + 0 comments

    for typescript, seems it will never reach the required performance if not implementing min heap on my own?

    this is the best i can produce so far while still timeout on a few cases

    function cookies(k: number, c: number[]): number {
        // Write your code here
        // console.log(k, c);
        c.sort((a, b) => a>b ? 1 : -1);
        if (c[0] < k && c.length === 1) return -1;
        
        let count = 0;
        while (c[0] < k && c.length > 1) {
            const mix = c[0] + 2*c[1];
            let index = c.findIndex(num => num >= mix);
            if (index === -1) {
                index = c.length;
            }
            // console.log('insert', mix, 'at index', index);
            
            c.splice(index, 0, mix);
            c.shift();
            c.shift();
            
            // c = c.slice(2, index).concat(mix).concat(c.slice(index));
            
            // c.push(mix);
            // c.sort((a, b) => a>b ? 1 : -1);
            count++;
            // console.log(c);
        }
    
        return c[0] >= k ? count : -1;
    }
    
  • + 0 comments

    So strange, I cannot pass tests like 21 when using Python3 heapq heapreplace with big numbers (wrong answer). Using heappop and heappush instead works fine. Most of the tests pass when using heapreplace. I wonder if there is an explanation besides me being a second tier programmer.

  • + 1 comment

    Decription is incorrect. It first mentioned >k then >=k.