1. Linear Search Over Speeds
Intuition
Iterate speed k starting from 1 upwards. For each k, sum ceil(pile / k). Return the first k where total hours <= h.
When to apply: Basic baseline.
Algorithm
- Step 1: Loop speed k from 1 to max(piles).
- Step 2: Calculate total hours for speed k.
- Step 3: If total hours <= h, return k.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: int minEatingSpeed(vector<int>& piles, int h) { int maxVal = 0; for (int p : piles) maxVal = max(maxVal, p); for (int k = 1; k <= maxVal; ++k) { long long totalHours = 0; for (int p : piles) { totalHours += (p + k - 1) / k; } if (totalHours <= h) return k; } return maxVal; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n * max(piles))— Can test up to 109 speeds, each taking O(n) time, resulting in TLE. - Space complexity:
O(1)— O(1) auxiliary space.