/* This solves the problem using linear search, which of course will be too slow, but it's a good first step to implementing binary search. */ #include #include #include #include using namespace std; class Solution { public: int minimizeMax(vector &nums, int p); }; int Solution::minimizeMax(vector &nums, int p) { int ans; int max; int num_pairs; int start, size; size_t i; sort(nums.begin(), nums.end()); max = nums[nums.size()-1]; start = 0; size = max+1; // This is because the range of answers is [0,max]. while (size > 1) { ans = start+size/2-1; num_pairs = 0; for (i = 1; i < nums.size(); i++) { if (nums[i] - nums[i-1] <= ans) { num_pairs++; i++; } } if (num_pairs >= p) { size /= 2; } else { start += size/2; size -= size/2; } } return start; } /* Read in nums and p, and call the method. */ int main() { vector nums; int p; Solution s; while (cin >> p) nums.push_back(p); nums.pop_back(); cout << s.minimizeMax(nums, p) << endl; return 0; }