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:
'U': Move up by 1 unit.'D': Move down by 1 unit.'L': Move left by 1 unit.'R': Move right by 1 unit.'_': Can be independently replaced with any one of 'U', 'D', 'L', or 'R'.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:
'L': (0, 0) -> (-1, 0)'_' treated as 'D': (-1, 0) -> (-1, -1)'D': (-1, -1) -> (-1, -2)'_' treated as 'L': (-1, -2) -> (-2, -2)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:
'U': (0, 0) -> (0, 1)'_' treated as 'U': (0, 1) -> (0, 2)'R': (0, 2) -> (1, 2)The final Manhattan distance from the origin is |0 - 1| + |0 - 2| = 3.
Constraints:
1 <= moves.length <= 105moves consists of only 'U', 'D', 'L', 'R', and '_'.Problem Overview: You are given a sequence of moves on a 2D grid using directions like N, S, E, and W. After performing all moves, the goal is to maximize the final Manhattan distance from the origin. Some moves can be modified, so the challenge is choosing changes that push the final position as far from (0,0) as possible.
Approach 1: Brute Force Direction Replacement (Exponential)
The most direct idea is to try all possible ways to modify the allowed moves. For every changeable move, replace it with each of the four directions and simulate the final position. After executing the entire sequence, compute the Manhattan distance |x| + |y|. This approach explores a large search space because each modification multiplies the number of possibilities. Time complexity grows exponentially (roughly O(4^k * n)), and space complexity is O(1) excluding recursion. This method only works for extremely small inputs and mainly helps build intuition about how direction choices affect the final coordinates.
Approach 2: Count Directions and Greedy Adjustments (O(n))
A more practical observation: the final Manhattan distance depends only on the net horizontal and vertical displacement. Moves E and W affect the x-axis, while N and S affect the y-axis. By counting each direction, you can compute the base displacement x = E - W and y = N - S. If modifications are allowed, changing a move that opposes your target direction increases distance the most (often by 2 units because it flips direction). A greedy strategy converts the most harmful moves first. Iterating through the string once to collect counts gives O(n) time and O(1) space.
Approach 3: Quadrant Maximization Trick (Optimal O(n))
The Manhattan distance can be rewritten as |x| + |y| = max(sx * x + sy * y) where sx and sy are either +1 or -1. That means the optimal result must correspond to one of four quadrants. For each quadrant, treat moves aligned with that direction as +1 and opposite moves as -1. Iterate through the sequence and compute the base score. If changes are allowed, flipping an unfavorable move increases the score by 2. Apply modifications to the worst contributors until you run out of changes. Evaluate all four quadrant configurations and take the maximum. This runs in O(4n) time (effectively O(n)) with O(1) extra space.
Conceptually this solution relies on understanding greedy algorithms and how Manhattan distance behaves under sign transformations. Many candidates also derive it by modeling the path as coordinate deltas and evaluating directional bias, a common trick in grid mathematics and simulation problems.
Recommended for interviews: The quadrant maximization approach. Interviewers expect you to recognize that Manhattan distance can be transformed into four linear expressions and optimized greedily. Mentioning the brute-force idea shows you understand the search space, but deriving the O(n) greedy solution demonstrates strong problem-solving skills.
Solutions for this problem are being prepared.
Try solving it yourself| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Direction Replacement | O(4^k * n) | O(1) | Only useful for understanding the search space or extremely small inputs |
| Direction Counting + Greedy Changes | O(n) | O(1) | When modifications are limited and direction counts determine displacement |
| Quadrant Maximization (Optimal) | O(n) | O(1) | Best general solution; evaluates all Manhattan sign combinations efficiently |
Practice Maximum Manhattan Distance After All Moves with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor