Approach
Sorting and greedy selection
For Allocate Mailboxes, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 42 lines of C++ from the credited upstream file 1478.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int minDistance(vector<int>& houses, int k) {4 const int n = houses.size();5 vector<vector<int>> mem(n, vector<int>(k + 1, INT_MAX));6 7 8 vector<vector<int>> cost(n, vector<int>(n));9 10 ranges::sort(houses);11 12 for (int i = 0; i < n; ++i)13 for (int j = i + 1; j < n; ++j) {14 const int median = houses[(i + j) / 2];15 for (int x = i; x <= j; ++x)16 cost[i][j] += abs(houses[x] - median);17 }18 19 return minDistance(houses, 0, k, cost, mem);20 }21 22 private:23 static constexpr int kMax = 1'000'000;24 25 26 int minDistance(const vector<int>& houses, int i, int k,27 const vector<vector<int>>& cost, vector<vector<int>>& mem) {28 if (i == houses.size() && k == 0)29 return 0;30 if (i == houses.size() || k == 0)31 return kMax;32 if (mem[i][k] != INT_MAX)33 return mem[i][k];34 35 for (int j = i; j < houses.size(); ++j)36 mem[i][k] = min(37 mem[i][k], cost[i][j] + minDistance(houses, j + 1, k - 1, cost, mem));38 39 return mem[i][k];40 }41};42