Jesse and Cookies

  • + 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;
    }