LeetCode in Kotlin

3968. Maximum Manhattan Distance After All Moves

Medium

You are given a string moves consisting of the characters 'U', 'D', 'L', 'R', and '_'.

Starting from the origin (0, 0), each character represents one move on a 2D plane:

Return the maximum Manhattan distance from the origin that can be achieved after all moves have been performed.

Example 1:

Input: moves = “L_D_”

Output: 4

Explanation:

One optimal choice is:

The final Manhattan distance from the origin is |0 - (-2)| + |0 - (-2)| = 4.

Example 2:

Input: moves = “U_R”

Output: 3

Explanation:

One optimal choice is:

The final Manhattan distance from the origin is |0 - 1| + |0 - 2| = 3.

Constraints:

Solution

import kotlin.math.abs

class Solution {
    fun maxDistance(s: String): Int {
        val d = IntArray(96)
        for (c in s.toCharArray()) {
            d[c.code]++
        }
        return abs(d['U'.code] - d['D'.code]) + abs(d['L'.code] - d['R'.code]) + d['_'.code]
    }
}