1. Linear Distance Check
Intuition
Sort array. Loop distance d from 1 to stalls[n-1] - stalls[0]. Return d - 1 when canPlace(d, k) becomes false.
When to apply: Basic baseline check.
Algorithm
- Step 1: Sort stalls array.
- Step 2: Loop distance d from 1 upwards.
- Step 3: If canPlace(d, k) is false, return d - 1.
- Step 4: Return max possible distance.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; int aggressiveCows(vector<int>& stalls, int k) { sort(stalls.begin(), stalls.end()); int maxDist = stalls.back() - stalls.front(); for (int d = 1; d <= maxDist; ++d) { int count = 1, last = stalls[0]; for (int i = 1; i < (int)stalls.size(); ++i) { if (stalls[i] - last >= d) { count++; last = stalls[i]; } } if (count < k) return d - 1; } return maxDist;} int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n log n + n * (max_stall - min_stall))— Sorting takes O(n log n), then distance range can be up to 109. - Space complexity:
O(1)— O(1) memory.