../ Competitive Programming
-rw-r--r--aguang1.1 KiB1 min read

Leet Code Daily 2024-06-20 - Magnetic Force Between Two Balls

Solution

Binary search.

Code

c++
class Solution {
public:
    // Given `position` sorted in increasing order and `min_dis`,
    // returns the maximum number of balls possible.
    int maxBalls(vector<int>& position, int min_dis) {
        int prev_pos = position[0], ret = 1;
        for (int i = 1; i < position.size(); i++) {
            if (position[i] - prev_pos >= min_dis) {
                prev_pos = position[i];
                ret++;
            }
        }
        return ret;
    }

    int maxDistance(vector<int>& position, int m) {
        sort(position.begin(), position.end());
        int low = 0, high = position[position.size() - 1] - position[0];
        while (low < high) {
            int mid = (low + high) / 2 + 1;
            if (maxBalls(position, mid) >= m) {
                low = mid;
            } else {
                high = mid - 1;
            }
        }
        return low;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window