The Wayback Machine - https://web.archive.org/web/20241008151544/https://www.geeksforgeeks.org/koko-eating-bananas/
Open In App

Koko Eating Bananas

Last Updated : 27 Oct, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given N piles of bananas, the ith pile has piles[i] bananas and H hours time until guards return (N < H). Find the minimum (S) bananas to eat per hour such that Koko can eat all the bananas within H hours. Each hour, Koko chooses some pile of bananas and eats S bananas from that pile. If the pile has less than S bananas, then she consumes all of them, and won’t eat any more bananas during that hour. 

Examples:

Input: piles = [3, 6, 7, 11], H = 8
Output: 4
Explanation:  Koko will eat 4 bananas per hour to finish all the bananas

Input: piles = [30, 11, 23, 4, 20], H = 6
Output: 23
Explanation:  Koko will eat 23 bananas per hour to finish all the bananas

 

Naive Approach: Koko must eat at least one banana per hour. Let lower bound be start. The maximum number of bananas Koko can eat in one hour is the maximum number of bananas from all piles. This is the maximum possible value of S. Let upper bound ends. Having search interval from start to end and using linear search, for every value of S, it can be checked if this speed of eating bananas is valid or not. The first valid value of S will be the slowest speed and the desired answer.

Time Complexity: O(N * W), where W is maximum bananas from all piles 

Approach: Given problem can be solved efficiently by using binary search on answer technique:

  • Create a boolean function to check if the chosen speed (bananas/hour) is enough to eat all bananas within given H hours time or not
  • Lower limit of S is 1 banana/hr as Koko must eat one banana per hour, and Upper limit is the maximum bananas of all piles
  • Apply binary search on the possible answer range to get minimum value of S
    • If the boolean function satisfies the mid value reduce higher to mid
    • Else update lower limit to mid + 1

C++




// C++ implementation for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
bool check(vector<int>& bananas, int mid_val, int H)
{
    int time = 0;
    for (int i = 0; i < bananas.size(); i++) {
 
        // to get the ceil value
        if (bananas[i] % mid_val != 0) {
 
            // in case of odd number
            time += ((bananas[i] / mid_val) + 1);
        }
        else {
 
            // in case of even number
            time += (bananas[i] / mid_val);
        }
    }
 
    // check if time is less than
    // or equals to given hour
    if (time <= H) {
        return true;
    }
    else {
        return false;
    }
}
 
int minEatingSpeed(vector<int>& piles, int H)
{
 
    // as minimum speed of eating must be 1
    int start = 1;
 
    // Maximum speed of eating
    // is the maximum bananas in given piles
    int end = *max_element(piles.begin(), piles.end());
 
    while (start < end) {
        int mid = start + (end - start) / 2;
 
        // Check if the mid(hours) is valid
        if ((check(piles, mid, H)) == true) {
 
            // If valid continue to search
            // lower speed
            end = mid;
        }
        else {
            // If cant finish bananas in given
            // hours, then increase the speed
            start = mid + 1;
        }
    }
    return end;
}
 
// Driver code
int main()
{
    vector<int> piles = { 30, 11, 23, 4, 20 };
    int H = 6;
    cout << minEatingSpeed(piles, H);
    return 0;
}


Java




// Java implementation for the above approach
 
 
import java.util.*;
 
class GFG{
 
static boolean check(int[] bananas, int mid_val, int H)
{
    int time = 0;
    for (int i = 0; i < bananas.length; i++) {
 
        // to get the ceil value
        if (bananas[i] % mid_val != 0) {
 
            // in case of odd number
            time += ((bananas[i] / mid_val) + 1);
        }
        else {
 
            // in case of even number
            time += (bananas[i] / mid_val);
        }
    }
 
    // check if time is less than
    // or equals to given hour
    if (time <= H) {
        return true;
    }
    else {
        return false;
    }
}
 
static int minEatingSpeed(int []piles, int H)
{
 
    // as minimum speed of eating must be 1
    int start = 1;
 
    // Maximum speed of eating
    // is the maximum bananas in given piles
    int end = Arrays.stream(piles).max().getAsInt();
 
    while (start < end) {
        int mid = start + (end - start) / 2;
 
        // Check if the mid(hours) is valid
        if ((check(piles, mid, H)) == true) {
 
            // If valid continue to search
            // lower speed
            end = mid;
        }
        else {
            // If cant finish bananas in given
            // hours, then increase the speed
            start = mid + 1;
        }
    }
    return end;
}
 
// Driver code
public static void main(String[] args)
{
    int []piles = { 30, 11, 23, 4, 20 };
    int H = 6;
    System.out.print(minEatingSpeed(piles, H));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python implementation for the above approach
def check(bananas, mid_val, H):
  time = 0;
  for i in range(len(bananas)):
     
    # to get the ceil value
    if (bananas[i] % mid_val != 0):
       
      # in case of odd number
      time += bananas[i] // mid_val + 1;
    else:
       
      # in case of even number
      time += bananas[i] // mid_val
 
  # check if time is less than
  # or equals to given hour
  if (time <= H):
    return True;
  else:
    return False;
   
def minEatingSpeed(piles, H):
  # as minimum speed of eating must be 1
  start = 1;
 
  # Maximum speed of eating
  # is the maximum bananas in given piles
  end = sorted(piles.copy(), reverse=True)[0]
 
  while (start < end):
    mid = start + (end - start) // 2;
 
    # Check if the mid(hours) is valid
    if (check(piles, mid, H) == True):
       
      # If valid continue to search
      # lower speed
      end = mid;
    else:
       
      # If cant finish bananas in given
      # hours, then increase the speed
      start = mid + 1;
  return end;
 
# Driver code
piles = [30, 11, 23, 4, 20];
H = 6;
print(minEatingSpeed(piles, H));
 
# This code is contributed by gfgking.


C#




// C# implementation for the above approach
using System;
using System.Linq;
public class GFG{
 
static bool check(int[] bananas, int mid_val, int H)
{
    int time = 0;
    for (int i = 0; i < bananas.Length; i++) {
 
        // to get the ceil value
        if (bananas[i] % mid_val != 0) {
 
            // in case of odd number
            time += ((bananas[i] / mid_val) + 1);
        }
        else {
 
            // in case of even number
            time += (bananas[i] / mid_val);
        }
    }
 
    // check if time is less than
    // or equals to given hour
    if (time <= H) {
        return true;
    }
    else {
        return false;
    }
}
 
static int minEatingSpeed(int []piles, int H)
{
 
    // as minimum speed of eating must be 1
    int start = 1;
 
    // Maximum speed of eating
    // is the maximum bananas in given piles
    int end = piles.Max();
 
    while (start < end) {
        int mid = start + (end - start) / 2;
 
        // Check if the mid(hours) is valid
        if ((check(piles, mid, H)) == true) {
 
            // If valid continue to search
            // lower speed
            end = mid;
        }
        else {
            // If cant finish bananas in given
            // hours, then increase the speed
            start = mid + 1;
        }
    }
    return end;
}
 
// Driver code
public static void Main(String[] args)
{
    int []piles = { 30, 11, 23, 4, 20 };
    int H = 6;
    Console.Write(minEatingSpeed(piles, H));
}
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
// Javascript implementation for the above approach
 
function check(bananas, mid_val, H) {
  let time = 0;
  for (let i = 0; i < bananas.length; i++) {
    // to get the ceil value
    if (bananas[i] % mid_val != 0) {
      // in case of odd number
      time += Math.floor(bananas[i] / mid_val) + 1;
    } else {
      // in case of even number
      time += Math.floor(bananas[i] / mid_val);
    }
  }
 
  // check if time is less than
  // or equals to given hour
  if (time <= H) {
    return true;
  } else {
    return false;
  }
}
 
function minEatingSpeed(piles, H) {
  // as minimum speed of eating must be 1
  let start = 1;
 
  // Maximum speed of eating
  // is the maximum bananas in given piles
  let end = [...piles].sort((a, b) => b - a)[0];
 
  while (start < end) {
    let mid = start + Math.floor((end - start) / 2);
 
    // Check if the mid(hours) is valid
    if (check(piles, mid, H) == true) {
      // If valid continue to search
      // lower speed
      end = mid;
    } else {
      // If cant finish bananas in given
      // hours, then increase the speed
      start = mid + 1;
    }
  }
  return end;
}
 
// Driver code
 
let piles = [30, 11, 23, 4, 20];
let H = 6;
document.write(minEatingSpeed(piles, H));
 
</script>


 
 

Output

23

 

Time Complexity:  O(N log W) (W is the max bananas from all piles)
Auxiliary Space: O(1)

 



Similar Reads

Array Data Structure Guide
An array data structure is a fundamental concept in computer science that stores a collection of elements in a contiguous block of memory. It allows for efficient access to elements using indices and is widely used in programming for organizing and manipulating data. Learn Basics of Array: Introduction to Arrays – Data Structure and Algorithm Tutor
3 min read
Linked List Data Structure
A linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. What is a Linked List? A linked list is a linear data structure that consists of a series of nodes connected
4 min read
Binary Search Tree
A Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the parent node. This hie
3 min read
Dynamic Programming or DP
Dynamic Programming is a method used in mathematics and computer science to solve complex problems by breaking them down into simpler subproblems. By solving each subproblem only once and storing the results, it avoids redundant computations, leading to more efficient solutions for a wide range of problems. This article provides a detailed explorat
7 min read
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. For Example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character wit
6 min read
Queue Data Structure
A Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. Queues are commonly used in various algorithms and applications for their simplicity and effi
3 min read
Stack Data Structure
A Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first, comes out last. Table of Content What is Stack D
4 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. In this tutorial, we will explore the most commonly used data structures, including arrays, linke
10 min read
Learn Data Structures and Algorithms | DSA Tutorial
Data Structures and Algorithms (DSA) refer to the study of methods for organizing and storing data and the design of procedures (algorithms) for solving problems, which operate on these data structures. DSA is one of the most important skills that every computer science student must have. It is often seen that people with good knowledge of these te
15+ min read
Top 100 Data Structure and Algorithms DSA Interview Questions Topic-wise
DSA has been one of the most popular go-to topics for any interview, be it college placements, software developer roles, or any other technical roles for freshers and experienced to land a decent job. If you are among them, you already know that it is not easy to find the best DSA interview questions among the vast pool of available problems. So he
4 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of the node. The AVL tree is named after its inventors, Georgy
3 min read
Top 50 Array Coding Problems for Interviews
Here is the collection of the Top 50 list of frequently asked interview questions on arrays. Problems in this Article are divided into three Levels so that readers can practice according to the difficulty level step by step. Level 1Problems Practice Find the Minimum and Maximum Element in an Array Solve Array Reverse Solve Write a Program to Cyclic
3 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the first pass, the maximum element goes to end (its cor
8 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element and swap it with the first element. This way we get
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Table of Content What is Binary Search Algorithm?Conditions to apply Binary Search Algorithm in a Data St
15+ min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. Table of Content How does QuickSort Algorithm work? Working of Partition Algorithm with IllustrationIllustration of QuickSort Algor
13 min read
Convert Infix expression to Postfix expression
Write a program to convert an Infix expression to Postfix form. Infix expression: The expression of the form "a operator b" (a + b) i.e., when an operator is in-between every pair of operands.Postfix expression: The expression of the form "a b operator" (ab+) i.e., When every pair of operands is followed by an operator. Examples: Input: A + B * C +
13 min read
Heap Sort - Data Structures and Algorithms Tutorials
Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use Binary Heap so that we can quickly find and move t
15 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a sorting algorithm that follows the divide-and-conquer approach. It works by recursively dividing the input array into smaller subarrays and sorting those subarrays then merging them back together to obtain the sorted array. In simple terms, we can say that the process of merge sort is to divide the array into two halves, sort each h
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. Then, you pick a card from the unsorted group and p
10 min read
How to find Shortest Paths from Source to all Vertices using Dijkstra's Algorithm
Given a weighted graph and a source vertex in the graph, find the shortest paths from the source to all the other vertices in the given graph. Note: The given graph does not contain any negative edge. Examples: Input: src = 0, the graph is shown below. Output: 0 4 12 19 21 11 9 8 14 Explanation: The distance from 0 to 1 = 4. The minimum distance fr
15+ min read
Prim’s Algorithm for Minimum Spanning Tree (MST)
Introduction to Prim's algorithm:We have discussed Kruskal's algorithm for Minimum Spanning Tree. Like Kruskal's algorithm, Prim’s algorithm is also a Greedy algorithm. This algorithm always starts with a single node and moves through several adjacent nodes, in order to explore all of the connected edges along the way. The algorithm starts with an
15+ min read
Breadth First Search or BFS for a Graph
Breadth First Search (BFS) is a fundamental graph traversal algorithm. It begins with a node, then first traverses all its adjacent. Once all adjacent are visited, then their adjacent are traversed. This is different from DFS in a way that closest vertices are visited before others. We mainly traverse vertices level by level. A lot of popular graph
15+ min read
0/1 Knapsack Problem
Prerequisites: Introduction to Knapsack Problem, its Types and How to solve them Given N items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum
15+ min read
Depth First Search or DFS for a Graph
Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. Like Trees, we traverse all adjacent one by one, when we traverse an adjacent, we finish traversal of all vertices reachable through the adjacent completely. After we finish one adjacent and its reachable, we go to the next adjacent and finish all reachable th
15+ min read
Array Reverse - Complete Tutorial
Given an array arr[], the task is to reverse the array. Reversing an array means rearranging the elements such that the first element becomes the last, the second element becomes second last and so on. Examples: Input: arr[] = {1, 4, 3, 2, 6, 5} Output: {5, 6, 2, 3, 4, 1}Explanation: The first element 1 moves to last position, the second element 4
15+ min read
Reverse a Linked List
Given a linked list, the task is to reverse the linked list by changing the links between nodes. Examples: Input: Linked List = 1 -> 2 -> 3 -> 4 -> NULL Output: Reversed Linked List = 4 -> 3 -> 2 -> 1 -> NULL Input: Linked List = 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: Reversed Linked List = 5 -> 4 -> 3 -
15+ min read
Tree Traversal Techniques
Tree Traversal techniques include various ways to visit all the nodes of the tree. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. In this article, we will discuss about all the tree traversal techniques along with their uses. Table o
15+ min read
Maximum Subarray Sum - Kadane's Algorithm
Given an array arr[], the task is to find the subarray that has the maximum sum and return its sum. Examples: Input: arr[] = {2, 3, -8, 7, -1, 2, 3}Output: 11Explanation: The subarray {7, -1, 2, 3} has the largest sum 11. Input: arr[] = {-2, -4}Output: -2Explanation: The subarray {-2} has the largest sum -2. Input: arr[] = {5, 4, 1, 7, 8}Output: 25
10 min read
Article Tags :
Practice Tags :