LeetCode in Kotlin

2467. Most Profitable Path in a Tree

Medium

There is an undirected tree with n nodes labeled from 0 to n - 1, 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.

At every node i, there is a gate. You are also given an array of even integers amount, where amount[i] represents:

The game goes on as follows:

Return the maximum net income Alice can have if she travels towards the optimal leaf node.

Example 1:

Input: edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, amount = [-2,4,2,-4,6]

Output: 6

Explanation:

The above diagram represents the given tree. The game goes as follows:

Alice’s net income is now -2.

Since they reach here simultaneously, they open the gate together and share the reward.

Alice’s net income becomes -2 + (4 / 2) = 0.

Bob moves on to node 0, and stops moving.

Now, neither Alice nor Bob can make any further moves, and the game ends.

It is not possible for Alice to get a higher net income.

Example 2:

Input: edges = [[0,1]], bob = 1, amount = [-7280,2350]

Output: -7280

Explanation:

Alice follows the path 0->1 whereas Bob follows the path 1->0.

Thus, Alice opens the gate at node 0 only. Hence, her net income is -7280.

Constraints:

Solution

class Solution {
    fun mostProfitablePath(edges: Array<IntArray>, bob: Int, amount: IntArray): Int {
        // Time: O(E); Space: O(N + E)
        // build graph
        val graph: Array<MutableList<Int>> = Array(amount.size) { ArrayList<Int>() }
        for (edge in edges) {
            graph[edge[0]].add(edge[1])
            graph[edge[1]].add(edge[0])
        }
        return helperDfs(graph, 0, bob, amount, BooleanArray(amount.size), 1)[0]
    }

    // Time: O(N); Space: O(N)
    private fun helperDfs(
        graph: Array<MutableList<Int>>,
        node: Int,
        bob: Int,
        amount: IntArray,
        seen: BooleanArray,
        height: Int
    ): IntArray {
        var res = Int.MIN_VALUE
        seen[node] = true
        var bobPathLen = if (node == bob) 1 else 0
        for (nextNode in graph[node]) {
            if (seen[nextNode]) continue
            val tmp = helperDfs(graph, nextNode, bob, amount, seen, height + 1)
            if (tmp[1] > 0) bobPathLen = tmp[1] + 1
            res = Math.max(res, tmp[0])
        }
        if (bobPathLen in 1..height) {
            if (bobPathLen == height) amount[node] = amount[node] / 2 else amount[node] = 0
        }
        return intArrayOf(if (res == Int.MIN_VALUE) amount[node] else amount[node] + res, bobPathLen)
    }
}