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
- 39 lines of Java from the credited upstream file 1478.java.
- 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 int minDistance(int[] houses, int k) {3 final int n = houses.length;4 int[][] mem = new int[n][k + 1];5 6 7 int[][] cost = new int[n][n];8 9 Arrays.stream(mem).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));10 Arrays.sort(houses);11 12 for (int i = 0; i < n; ++i)13 for (int j = i + 1; j < n; ++j) {14 int median = houses[(i + j) / 2];15 for (int x = i; x <= j; ++x)16 cost[i][j] += Math.abs(houses[x] - median);17 }18 19 return minDistance(houses, 0, k, cost, mem);20 }21 22 private static final int MAX = 1_000_000;23 24 25 private int minDistance(int[] houses, int i, int k, int[][] cost, int[][] mem) {26 if (i == houses.length && k == 0)27 return 0;28 if (i == houses.length || k == 0)29 return MAX;30 if (mem[i][k] != Integer.MAX_VALUE)31 return mem[i][k];32 33 for (int j = i; j < houses.length; ++j)34 mem[i][k] = Math.min(mem[i][k], cost[i][j] + minDistance(houses, j + 1, k - 1, cost, mem));35 36 return mem[i][k];37 }38}39