Poor Pigs Problem


Description

LeetCode Problem 458.

There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.

You can feed the pigs according to these steps:

  • Choose some live pigs to feed.
  • For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time.
  • Wait for minutesToDie minutes. You may not feed any other pigs during this time.
  • After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
  • Repeat this process until you run out of time.

Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.

Example 1:

1
2
Input: buckets = 1000, minutesToDie = 15, minutesToTest = 60
Output: 5

Example 2:

1
2
Input: buckets = 4, minutesToDie = 15, minutesToTest = 15
Output: 2

Example 3:

1
2
Input: buckets = 4, minutesToDie = 15, minutesToTest = 30
Output: 2

Constraints:

  • 1 <= buckets <= 1000
  • 1 <=minutesToDie <=minutesToTest <= 100


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
    int poorPigs(long double buckets, long double poisonTime, long double totalTime) {
    	// Total Rounds (T) = totalTime/poisonTime
        // Assume p = no of pigs that will give us the result
        // Therefore, (T+1)^p >= buckets
        // Taking log on both sides, p = log(buckets)/log(T+1);
        // Return ceil of p 
        return ceil(log(buckets) / log(totalTime / poisonTime + 1));
    }
};




Related Posts

Valid Permutations For DI Sequence Problem

LeetCode 903. You are given a string s of length...

Tallest Billboard Problem

LeetCode 956. You are installing a billboard and want it...

Sum Of Subarray Minimums Problem

LeetCode 907. Given an array of integers arr, find the...

Stone Game Problem

LeetCode 877. Alice and Bob play a game with piles...

Split Array With Same Average Problem

LeetCode 805. You are given an integer array nums.

Soup Servings Problem

LeetCode 808. There are two types of soup, type A...