[LeetCode] Maximum Manhattan Distance After All Moves

3968. Maximum Manhattan Distance After All Moves

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int maxDistance(string moves) {
int y = 0, x = 0, any = 0;
for(auto& m : moves) {
if(m == 'U') y++;
if(m == 'D') y--;
if(m == 'L') x++;
if(m == 'R') x--;
if(m == '_') any++;
}
return abs(y) + abs(x) + any;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/maximum-manhattan-distance-after-all-moves/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.