753. Stones in Line
A gardener has placed ornamental stones on integer points of a huge field. The entry stones[i] = [x, y] gives the row x and the column y of stone i, and no two stones occupy the same point. A stone may be picked up only if at least one other stone that is still on the field lies in the same row or in the same column as it.
The gardener keeps picking up stones, one at a time, for as long as some stone can be picked up. Return the largest possible number of stones that can be picked up in total. The answer depends only on stones, not on the order in which stones are chosen, as long as the best strategy is used.
Example 1
- Input:
- stones = [[1,1],[1,4],[3,4],[5,9]]
- Output:
- 2
- Explanation:
The first three stones are linked through row 1 and column 4, so two of them can be removed; the stone at (5, 9) is alone and must stay.
Example 2
- Input:
- stones = [[2,3],[4,5],[6,7]]
- Output:
- 0
- Explanation:
No two stones share a row or a column, so none can be picked up.
Example 3
- Input:
- stones = [[0,0],[0,1],[1,0],[1,1]]
- Output:
- 3
- Explanation:
All four stones are in one connected block, so three of them can be removed, leaving a single stone.
Constraints
- 1 ≤ stones.length ≤ 105
- 0 ≤ x, y ≤ 109
- All points are distinct
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 200 msC++ 50 msJava 100 msJavaScript 100 msTypeScript 100 ms
Expected complexity
- Time
- O(n * alpha(n))
- Space
- O(n)