LeetCode-in-Java

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

public class Solution {
    public int maxDistance(String s) {
        int[] d = new int[96];
        for (char c : s.toCharArray()) {
            d[c]++;
        }
        return Math.abs(d['U'] - d['D']) + Math.abs(d['L'] - d['R']) + d['_'];
    }
}