Magnetic Force Between Two Balls LeetCode solution in C++
1// OJ:2// https://leetcode.com/contest/weekly-contest-202/problems/magnetic-force-between-two-balls/3// Author: github.com/lzl124631x4// Time: O(log(max(A)) * N + NlogN)5// Space: O(1)6class Solution {7bool valid(vector<int> &A, int M, int m) {8int prev = 0;9for (int i = 1, j = 1; i < m; ++i) {10while (j < A.size() && A[j] < A[prev] + M) ++j;11if (j >= A.size()) return false;12prev = j;13}14return true;15}1617public:18int maxDistance(vector<int> &A, int m) {19sort(begin(A), end(A));20if (m == 2) return A.back() - A[0];21int L = 1, R = A.back() - A[0];22while (L <= R) {23int M = (L + R) / 2;24if (valid(A, M, m))25L = M + 1;26else27R = M - 1;28}29return R;30}31};