• + 0 comments

    C++ solution using priority queue

    int cookies(int k, vector<int> A) {
        priority_queue <int, vector <int>, greater <int>> q; 
        for(int i = 0; i < A.size(); i++){
            q.push(A[i]);
        }
        int step = 0;
        bool check = true;
        while(1){
            int min_s1 = q.top(); //1st smallest element
            q.pop();
            if(q.empty()){
                if(min_s1 < k) check = false;
                break;
            }
            if(min_s1 >= k) break;
            int min_s2 = q.top(); //2nd smallest element
            q.pop();
            int new_s = min_s1 + 2 * min_s2;
            q.push(new_s);
            step++;
        }
        if(!check) step = -1;
        return step;
    }