luoheng
10/27/2019 - 12:38 PM

twoCitySchedCost

func partition(costs [][]int, s, e, k int) {
    p, n := costs[e-1][0] - costs[e-1][1], s
    for i := s; i < e; i++ {
        if costs[i][0] - costs[i][1] <= p {
            costs[i], costs[n] = costs[n], costs[i]
            n++
        }
    }
    if n - s > k {
        partition(costs, s, n - 1, k)
    } else if n - s < k {
        partition(costs, n, e, k - n + s)
    }
}

func twoCitySchedCost(costs [][]int) int {
    partition(costs, 0, len(costs), len(costs)/2)
    sum := 0
    for i := 0; i < len(costs)/2; i++ {
        sum += costs[i][0]
    }
    for i := len(costs)/2; i < len(costs); i++ {
        sum += costs[i][1]
    }
    return sum
}