/* Driver and binary search solution for Leetcode problem "Koko Eating Bananas". */ #include #include using namespace std; class Solution { public: int minEatingSpeed(vector& piles, int h); }; int Solution::minEatingSpeed(vector& piles, int h) { int start, size, maxpile, mid; size_t i; long long timesteps, for_pile; /* Calculate the maximum pile size. */ maxpile = piles[0]; for (i = 0; i < piles.size(); i++) if (piles[i] > maxpile) maxpile = piles[i]; /* We want our range to start at one and end at maxpile (including maxpile). So we set start to 1 and size to maxpile. Remember size means that start+size is one past the last element in our region. */ start = 1; size = maxpile; while (size > 1) { /* You want to test the highest value in the first half of the values ( the last value in the blue region of the picture. */ mid = start + size/2 - 1; /* Timesteps is the total timesteps if k is set to mid. */ timesteps = 0; for (i = 0; i < piles.size(); i++) { for_pile = piles[i] / mid; if (piles[i]%mid != 0) for_pile++; timesteps += for_pile; } // printf("Start: %d. Size: %d Mid: %d. Timesteps: %lld\n", start, size, mid, timesteps); /* If timesteps is too big, then you know that the answer is in the second half of the range. You can throw out the first half. */ if (timesteps > h) { start += size/2; size -= size/2; /* Otherwise, the answer is in the first half of the range, so toss out the second half. */ } else { size = size/2; } } return start; } int main() { vector p; int h; Solution s; while (cin >> h) p.push_back(h); /* Read the piles and h and put them into p */ p.pop_back(); /* Remove h from p. */ cout << s.minEatingSpeed(p, h) << endl; return 0; }