LeetCode in Kotlin

2285. Maximum Total Importance of Roads

Medium

You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1.

You are also given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.

You need to assign each city with an integer value from 1 to n, where each value can only be used once. The importance of a road is then defined as the sum of the values of the two cities it connects.

Return the maximum total importance of all roads possible after assigning the values optimally.

Example 1:

Input: n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]

Output: 43

Explanation: The figure above shows the country and the assigned values of [2,4,5,3,1].

The total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43.

It can be shown that we cannot obtain a greater total importance than 43.

Example 2:

Input: n = 5, roads = [[0,3],[2,4],[1,3]]

Output: 20

Explanation: The figure above shows the country and the assigned values of [4,3,2,5,1].

The total importance of all roads is 9 + 3 + 8 = 20.

It can be shown that we cannot obtain a greater total importance than 20.

Constraints:

Solution

class Solution {
    fun maximumImportance(n: Int, roads: Array<IntArray>): Long {
        val degree = IntArray(n)
        var maxdegree = 0
        for (r in roads) {
            degree[r[0]]++
            degree[r[1]]++
            maxdegree = Math.max(maxdegree, Math.max(degree[r[0]], degree[r[1]]))
        }
        val rank: MutableMap<Int, Int> = HashMap()
        var i = n
        while (i > 0) {
            for (j in 0 until n) {
                if (degree[j] == maxdegree) {
                    rank[j] = i--
                    degree[j] = Int.MIN_VALUE
                }
            }
            maxdegree = 0
            for (d in degree) {
                maxdegree = Math.max(maxdegree, d)
            }
        }
        var res: Long = 0
        for (r in roads) {
            res += (rank[r[0]]!! + rank[r[1]]!!).toLong()
        }
        return res
    }
}