LeetCode 1478: Allocate Mailboxes

Problem Description

Explanation:

To solve this problem, we can use dynamic programming. We will iterate over all possible ranges of houses to consider for placing a mailbox. For each range, we will calculate the cost of placing a mailbox at each possible position within that range. We will then keep track of the minimum total distance for each subproblem.

  1. Sort the houses array in ascending order.
  2. Initialize a 2D array dp[][] where dp[i][k] represents the minimum total distance for the first i houses with k mailboxes.
  3. Calculate the cost of placing a mailbox at each possible position within the range of houses.
  4. Update dp[i][k] by considering all possible partition points for the last mailbox placement.
  5. The final answer will be dp[n][k] where n is the number of houses.

Time Complexity:

The time complexity of this approach is O(n^2 * k), where n is the number of houses.

Space Complexity:

The space complexity of this approach is O(n * k).

Solutions

class Solution {
    public int minDistance(int[] houses, int k) {
        Arrays.sort(houses);
        int n = houses.length;
        int[][] dp = new int[n + 1][k + 1];
        
        for (int i = 0; i <= n; i++) {
            Arrays.fill(dp[i], Integer.MAX_VALUE);
        }
        
        for (int i = 1; i <= n; i++) {
            dp[i][1] = calculateCost(houses, 0, i - 1);
        }
        
        for (int i = 2; i <= n; i++) {
            for (int j = 2; j <= k; j++) {
                for (int x = 1; x < i; x++) {
                    dp[i][j] = Math.min(dp[i][j], dp[x][j - 1] + calculateCost(houses, x, i - 1));
                }
            }
        }
        
        return dp[n][k];
    }
    
    private int calculateCost(int[] houses, int start, int end) {
        int median = (start + end) / 2;
        int cost = 0;
        
        for (int i = start; i <= end; i++) {
            cost += Math.abs(houses[i] - houses[median]);
        }
        
        return cost;
    }
}

Loading editor...