I got the greedy intuition pretty fast, sort both arrays and use two pointers to match greedily within the distance constraint.
Recognize this as a bipartite matching problem with a secondary objective: first maximize the number of matched pairs (person-shop) where distance ≤ 5, then minimize total distance among maximum matchings. Propose a greedy approach after sorting both people and shops by position, using a two-pointer or priority queue to pair them optimally, and justify why greedy works for the 1D case.
Pro tip: Mention that you can model this as a min-cost max-flow problem but that a greedy solution is more efficient; then explain the greedy choice and prove it with an exchange argument to show you understand both correctness and optimization.
Restate the problem: maximize cardinality of matching where distance ≤ 5, then minimize sum of distances. Model as bipartite matching between people and shops with edge weights = distance.
Note that N and M may differ, and not all can be matched. Consider edge cases: no valid pairs, all within distance, multiple people/shops at same position.
Sort people and shops by position. Use two pointers: for each person in order, assign the nearest available shop within distance 5, but ensure it doesn't block a later person who has fewer options. Alternatively, use a priority queue to always match the leftmost person with the leftmost feasible shop.
Argue that the greedy choice (matching leftmost person to leftmost feasible shop) maximizes cardinality and minimizes total distance via an exchange argument: any optimal solution can be transformed to the greedy one without reducing matches or increasing distance.
Sorting takes O((N+M) log(N+M)). The greedy pass is O(N+M). Compare with min-cost max-flow which is O(V^2 E) or similar, highlighting efficiency. Mention that if distance constraint were larger, a different approach might be needed.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.