This is one of those problems where the clean idea matters more than the amount of code. For 1552. Magnetic Force Between Two Balls, the solution in this repository is mainly a binary search solution.
Guide
What?
The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: binary search, two pointers, greedy.
The notes already sitting in the source point us in the right direction:
- Binary search
Guide
When?
Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are check, maxDistance.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Binary search
02//Runtime: 440 ms, faster than 100.00% of C++ online submissions for Magnetic Force Between Two Balls.
03//Memory Usage: 57.9 MB, less than 33.33% of C++ online submissions for Magnetic Force Between Two Balls.
04class Solution {
05public:
06 int check(vector<int>& pos, int& m, int interval){
07 int count = 1;
08 int last = pos[0];
09
10 for(int& e : pos){
11 if(e - last >= interval){
12 ++count;
13 last = e;
14 if(count >= m) return true;
15 }
16 }
17
18 return false;
19 };
20
21 int maxDistance(vector<int>& pos, int m) {
22 sort(pos.begin(), pos.end());
23
24 int interval = (pos.back() - pos.front()) / (m-1);
25
26 int l = 1, r = interval;
27
28 //find right boundary
29 while(l <= r){
30 int mid = (l+r) >> 1;
31 // cout << l << ", " << mid << ", " << r << endl;
32 if(check(pos, m, mid)){
33 l = mid+1;
34 }else{
35 r = mid-1;
36 }
37 }
38
39 return r;
40 }
41};
Cost