LeetCode in Kotlin

2925. Maximum Score After Applying Operations on a Tree

Medium

There is an undirected tree with n nodes labeled from 0 to n - 1, and rooted at node 0. You are given a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

You are also given a 0-indexed integer array values of length n, where values[i] is the value associated with the ith node.

You start with a score of 0. In one operation, you can:

A tree is healthy if the sum of values on the path from the root to any leaf node is different than zero.

Return the maximum score you can obtain after performing these operations on the tree any number of times so that it remains healthy.

Example 1:

Input: edges = [[0,1],[0,2],[0,3],[2,4],[4,5]], values = [5,2,5,2,1,1]

Output: 11

Explanation: We can choose nodes 1, 2, 3, 4, and 5. The value of the root is non-zero. Hence, the sum of values on the path from the root to any leaf is different than zero. Therefore, the tree is healthy and the score is values[1] + values[2] + values[3] + values[4] + values[5] = 11. It can be shown that 11 is the maximum score obtainable after any number of operations on the tree.

Example 2:

Input: edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]], values = [20,10,9,7,4,3,5]

Output: 40

Explanation: We can choose nodes 0, 2, 3, and 4.

Therefore, the tree is healthy and the score is values[0] + values[2] + values[3] + values[4] = 40.

It can be shown that 40 is the maximum score obtainable after any number of operations on the tree.

Constraints:

Solution

import kotlin.math.min

class Solution {
    fun maximumScoreAfterOperations(edges: Array<IntArray>, values: IntArray): Long {
        var sum: Long = 0
        val n = values.size
        val adj: MutableList<MutableList<Int>> = ArrayList()
        for (i in 0 until n) {
            adj.add(ArrayList())
        }
        for (edge in edges) {
            adj[edge[0]].add(edge[1])
            adj[edge[1]].add(edge[0])
        }
        for (value in values) {
            sum += value.toLong()
        }
        val x = dfs(0, -1, adj, values)
        return sum - x
    }

    private fun dfs(node: Int, parent: Int, adj: List<MutableList<Int>>, values: IntArray): Long {
        if (adj[node].size == 1 && node != 0) {
            return values[node].toLong()
        }
        var sum: Long = 0
        for (child in adj[node]) {
            if (child != parent) {
                sum += dfs(child, node, adj, values)
            }
        }
        return min(sum, values[node].toLong())
    }
}