• Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
Friday, January 27, 2023
  • Login
Zeroplusfour
No Result
View All Result
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
No Result
View All Result
Zeroplusfour
No Result
View All Result
Home Code Solutions Hackerrank Algorithms

Jesse and Cookies – HackerRank Solution

Jesse and Cookies - HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

bhautik bhalala by bhautik bhalala
May 31, 2022
Reading Time: 1 min read
0
15 Days to learn SQL Hard SQL(Advanced)-Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution alt text

Spread the love

Table of Contents

  • Jesse and Cookies – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
  • Solutions of Algorithms Data Structures Hard HackerRank:
    • Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
  • 1 Month Preparation Kit Solutions – HackerRank
  • C++ Jesse and Cookies HackerRank Solution
  • Java Jesse and Cookies HackerRank Solution
  • Python 3 Jesse and Cookies HackerRank Solution
  • JavaScript Jesse and Cookies HackerRank Solution
  • C Jesse and Cookies HackerRank Solution
    • Leave a comment below
      • Related posts:

Jesse and Cookies – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

Solutions of Algorithms Data Structures Hard HackerRank:

Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts


1 Month Preparation Kit Solutions – HackerRank

 

 


C++ Jesse and Cookies HackerRank Solution


Copy Code Copied Use a different Browser

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#include <functional>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int N, K, ai;
    priority_queue<int, vector<int>, greater<int>> A;
    cin >> N >> K;
    for (int i = 0; i < N; ++i) {
        cin >> ai;
        A.push(ai);
    }
    int count = 0;
    while (A.top() < K) {
        if (A.size() < 2) {
            cout << "-1\n";
            return 0;
        }
        int m1 = A.top();
        A.pop();
        int m2 = A.top();
        A.pop();
        A.push(m1 + 2 * m2);
        count++;
    }
    cout << count << endl;
    return 0;
}

Java Jesse and Cookies HackerRank Solution


Copy Code Copied Use a different Browser

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int numCookies = sc.nextInt();
        int minSweetness = sc.nextInt();
        int count = 0;
        PriorityQueue<Integer> he = new PriorityQueue<Integer>(numCookies);
        for(int i = 0; i < numCookies; i++){
            int sweetness = sc.nextInt();
            he.add(sweetness);
        }
        while(he.peek() < minSweetness && he.size() > 1){
            int ne = he.poll() + 2*he.poll();
            he.add(ne);
            count++;
        }
        if(he.peek() >= minSweetness){
            System.out.println(count);
        } else{
            System.out.println(-1);
        }
    }
}

 



Python 3 Jesse and Cookies HackerRank Solution


Copy Code Copied Use a different Browser

from heapq import heapify, heappush, heappop

def get_number_mixes(cookies, minimum_value):
    cookies = list(cookies)
    heapify(cookies)
    count = 0
    while cookies[0] < minimum_value:
        if len(cookies) < 2:
            return -1
        heappush(cookies, heappop(cookies) + 2 * heappop(cookies))
        count += 1
    return count

N, K = map(int, input().split())
A = map(int, input().split())        
print(get_number_mixes(A, K))



JavaScript Jesse and Cookies HackerRank Solution


Copy Code Copied Use a different Browser

reachMinSweatness = (arr, target) => {
    const minHeap = new Heap();
    arr.forEach(el => minHeap.add(el));
    let count = 0;
    
    while (minHeap.min() < target) {
        if (minHeap.length() === 1) return -1;
        const firstMin = minHeap.extractMin();
        const secondMin = minHeap.extractMin();
        const combinedMins = firstMin * 1 + secondMin * 2;
        minHeap.add(combinedMins);
        count += 1;
    }
    
    return count;
}

class Heap {
    constructor() {
        this.store = [];
    }
    
    length() {
        return this.store.length;
    }
    
    min() {
        return this.store[0];
    }
    
    add(el) {
        this.store.push(el);
        this.heapifyUp();
    }
    
    extractMin() {
        const min = this.store[0];
        this.store[0] = this.store[this.store.length - 1];
        this.store.pop();
        this.heapifyDown();
        return min;
    }
    
    heapifyUp() {
        let currentElIdx = this.store.length - 1;
        let parentIdx = Math.floor((currentElIdx - 1) / 2);
        
        while (parentIdx >= 0 && this.store[currentElIdx] < this.store[parentIdx]) {
            const hold = this.store[currentElIdx];
            this.store[currentElIdx] = this.store[parentIdx];
            this.store[parentIdx] = hold;
            
            currentElIdx = parentIdx;
            parentIdx = Math.floor((currentElIdx - 1) / 2);
        }
        
        return this.store;
    }
    
    heapifyDown() {
        let parentIdx = 0;
        let childIndices = this.getChildIndices(parentIdx);
        
        while (childIndices.length > 0 
               && this.store[childIndices[0]] < this.store[parentIdx]
               || (childIndices[1] && this.store[childIndices[1]] < this.store[parentIdx])) {
            
            if (childIndices[1] && this.store[childIndices[1]] < this.store[childIndices[0]]) {
                const hold = this.store[childIndices[1]];
                this.store[childIndices[1]] = this.store[parentIdx];
                this.store[parentIdx] = hold;
                
                parentIdx = childIndices[1];
                childIndices = this.getChildIndices(parentIdx);
            } else {
                const hold = this.store[childIndices[0]];
                this.store[childIndices[0]] = this.store[parentIdx];
                this.store[parentIdx] = hold;
                
                parentIdx = childIndices[0];
                childIndices = this.getChildIndices(parentIdx);
            }
        }
        
        return this.store;
    }
    
    getChildIndices(parentIdx) {
        const childIndices = [];
        if ((parentIdx * 2 + 1) < this.store.length) childIndices.push(parentIdx * 2 + 1);
        if ((parentIdx * 2 + 2) < this.store.length) childIndices.push(parentIdx * 2 + 2);
        return childIndices   
    }
}


function processData(input) {
    const [metaData, data] = input.split('\n');
    const [n, target] = metaData.split(' ');
    const arr = data.split(' ').map(el => parseInt(el));
    const h = new Heap();
    //arr.forEach(el => h.add(el));
    //console.log(h.extractMin(), h.store)
    console.log(reachMinSweatness(arr, target));
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});



C Jesse and Cookies HackerRank Solution


Copy Code Copied Use a different Browser

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>

/* Global Variables*/
int *heap_array = NULL;
int heap_max_size = 0;
int heap_current_size = 0;

#define SIZE_OF_BLOCK_ALLOCATION  1000 

void heap_heapify_from_top (int counter) {
    int temp_val = 0;
    int child_counter;
    int has_left_child = 0;
    int has_right_child = 0;

    if ((2 * counter + 1) < heap_current_size)
        has_left_child = 1;

    if ((2 * counter + 2) < heap_current_size)
        has_right_child = 1;

    /* Now, let us find the lowest of the two children */
    if (has_left_child && has_right_child) {
        if (heap_array[2* counter + 1] < heap_array[2*counter + 2])
            child_counter = 2 * counter + 1;
        else
            child_counter = 2 * counter + 2;
    } else if (has_left_child) {
        child_counter = 2 * counter + 1;
    } else if (has_right_child) {
        child_counter = 2 * counter + 2;
    } else {
        return;
    }

    if (heap_array[counter] > heap_array[child_counter]) {
        temp_val = heap_array[counter];
        heap_array[counter] = heap_array[child_counter];
        heap_array[child_counter] = temp_val;
        heap_heapify_from_top(child_counter);
    }
    return;
}

int heap_extract () {
    int t = 0;
    if (heap_current_size == 0) {
        printf("The heap is empty\n");
        return -1;
    }

    t = heap_array[0];
    heap_array[0] = heap_array[heap_current_size-1];
    heap_current_size--;

    if (heap_current_size != 1) {
        heap_heapify_from_top(0);
    }
    return t;
}

 void heap_insert_heapify_from_bottom (int counter) {
     int parent = (int) floor((double)(counter-1)/2);
     int temp_val;

     if (counter == 0) {
         return;
     }

     if (heap_array[parent] > heap_array[counter]) {
         temp_val = heap_array[counter];
         heap_array[counter] = heap_array[parent];
         heap_array[parent] = temp_val;
     }

     heap_insert_heapify_from_bottom(parent);
 }

 int heap_add (int value) {
     if (heap_current_size == heap_max_size) {
         heap_max_size += SIZE_OF_BLOCK_ALLOCATION;
         heap_array = (void*)realloc(heap_array,
                         heap_max_size * sizeof(int));
         if (!heap_array) {
             printf("realloc failed\n");
             return -1;
         }
     }
     heap_array[heap_current_size] = value;
     heap_insert_heapify_from_bottom(heap_current_size);
     heap_current_size++;
     return 0;
 }

 int main (int argc, char *argv[]) {
    int n, k, i, temp=0, temp2=0, num_oper=0, temp_k;
    bool no_entry_with_max = true;

    scanf("%d %d", &n, &k);
    for (i = 0; i <n; i++) {
        scanf("%d", &temp);
        heap_add(temp);
    }

    temp = heap_extract();
    if (temp >= k) {
        printf("0\n");
        return 0;
    }
    while (temp < k && heap_current_size) {
        temp2 = heap_extract();
        temp_k = temp + 2 * temp2;
        num_oper += 1;
        heap_add(temp_k);
        if (temp_k >= k) {
            no_entry_with_max = false;
        }
        temp = heap_extract();
    }
    if (no_entry_with_max == true) {
        printf("-1\n");
    } else {
        printf("%d\n", num_oper);
    }
    return 0;
 }

 

Leave a comment below

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionJesse and Cookies – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDistant Pairs – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionThe Value of Friendship – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDrive – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSuperman Celebrates Diwali – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSales by Match – HackerRank Solution
Tags: Cc++14full solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptJesse and Cookiespypy 3Python 2python 3
ShareTweetPin
bhautik bhalala

bhautik bhalala

Related Posts

Leetcode All Problems Solutions
Code Solutions

Exclusive Time of Functions – LeetCode Solution

by admin
October 5, 2022
0
29

Exclusive Time of Functions - LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions...

Read more
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
32
Leetcode All Problems Solutions

Course Schedule III – LeetCode Solution

October 5, 2022
25
Leetcode All Problems Solutions

Maximum Product of Three Numbers – LeetCode Solution

September 11, 2022
52
Leetcode All Problems Solutions

Task Scheduler – LeetCode Solution

September 11, 2022
119
Leetcode All Problems Solutions

Valid Triangle Number – LeetCode Solution

September 11, 2022
28
Next Post
15 Days to learn SQL Hard SQL(Advanced)-Solution

Hackerland Radio Transmitters - HackerRank Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution

Queries with Fixed Length - HackerRank Solution

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

15 Days to learn SQL Hard SQL(Advanced)-SolutionJesse and Cookies – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDistant Pairs – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionThe Value of Friendship – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDrive – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSuperman Celebrates Diwali – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSales by Match – HackerRank Solution

Categories

  • Algorithms
  • Anime
  • Biography
  • Business
  • Code Solutions
  • Cosmos
  • Countdowns
  • Culture
  • Economy
  • Education
  • Entertainment
  • Finance
  • Games
  • Hackerrank
  • Health
  • How to
  • Investment
  • LeetCode
  • Lifestyle
  • LINUX SHELL
  • Manga
  • News
  • Opinion
  • Politics
  • Sports
  • SQL
  • Tech
  • Travel
  • Uncategorized
  • Updates
  • World
  • DMCA
  • Home
  • My account
  • Privacy Policy
  • Top Posts

Recent Blogs

Leetcode All Problems Solutions

Exclusive Time of Functions – LeetCode Solution

October 5, 2022
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Counter game – HackerRank Solution

May 31, 2022
7
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Jesse and Cookies – HackerRank Solution

May 25, 2022
33
Biography

Rupali Ganguly Net Worth, Age, Height , Achivements and more

September 8, 2022
0
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Liars – HackerRank Solution

May 26, 2022
42

© 2022 ZeroPlusFour - Latest News & Blog.

No Result
View All Result
  • Home
  • Category
    • Business
    • Culture
    • Economy
    • Lifestyle
    • Health
    • Travel
    • Opinion
    • Politics
    • Tech
  • Landing Page
  • Support Forum
  • Contact Us

© 2022 ZeroPlusFour - Latest News & Blog.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?