1478. Allocate Mailboxes Hard

@problem@discussion
#Array#Math#Dynamic Programming#Sorting



1/**
2 * [1478] Allocate Mailboxes
3 *
4 * Given the array houses where houses[i] is the location of the i^th house along a street and an integer k, allocate k mailboxes in the street.
5 * Return the minimum total distance between each house and its nearest mailbox.
6 * The test cases are generated so that the answer fits in a 32-bit integer.
7 *  
8 * Example 1:
9 * <img alt="" src="https://assets.leetcode.com/uploads/2020/05/07/sample_11_1816.png" style="width: 454px; height: 154px;" />
10 * Input: houses = [1,4,8,10,20], k = 3
11 * Output: 5
12 * Explanation: Allocate mailboxes in position 3, 9 and 20.
13 * Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 
14 * 
15 * Example 2:
16 * <img alt="" src="https://assets.leetcode.com/uploads/2020/05/07/sample_2_1816.png" style="width: 433px; height: 154px;" />
17 * Input: houses = [2,3,5,12,18], k = 2
18 * Output: 9
19 * Explanation: Allocate mailboxes in position 3 and 14.
20 * Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.
21 * 
22 *  
23 * Constraints:
24 * 
25 * 	1 <= k <= houses.length <= 100
26 * 	1 <= houses[i] <= 10^4
27 * 	All the integers of houses are unique.
28 * 
29 */
30pub struct Solution {}
31
32// problem: https://leetcode.com/problems/allocate-mailboxes/
33// discuss: https://leetcode.com/problems/allocate-mailboxes/discuss/?currentPage=1&orderBy=most_votes&query=
34
35// submission codes start here
36
37impl Solution {
38    pub fn min_distance(houses: Vec<i32>, k: i32) -> i32 {
39        0
40    }
41}
42
43// submission codes end
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn test_1478() {
51    }
52}
53


Back
© 2025 bowen.ge All Rights Reserved.