The Manhattan distance for a string of moves can be calculated as |count_N - count_S| + |count_E - count_W|, where each count represents the number of times a direction appears. Changing less frequent directions in either axis increases the distance, while changing more frequent ones decreases it. Only increasing the less frequent directions will maximize the Manhattan distance.
First, focus on modifying the less frequent vertical directions (N or S). If their count is greater than k, change only k of them; otherwise, change all and use any remaining modifications for the horizontal directions (E or W). Repeat this process for the horizontal axis with any leftover modifications. As you process the string, update and track the maximum Manhattan distance reached at any point.
classSolution {
public:int maxDistance(string s, int k) {
int n = s.size();
int north =0, south =0, east =0, west =0;
int maxDist =0;
for (int i =0; i < n; ++i) {
char ch = s[i];
if (ch =='N') north++;
elseif (ch =='S') south++;
elseif (ch =='E') east++;
elseif (ch =='W') west++;
// Calculate possible changes for vertical and horizontal
int vert = abs(north - south);
int hori = abs(east - west);
int remK = k;
// Try to maximize vertical axis
int minVert = min(north, south);
int vertChange = min(remK, minVert);
vert += vertChange *2;
remK -= vertChange;
// Try to maximize horizontal axis
int minHori = min(east, west);
int horiChange = min(remK, minHori);
hori += horiChange *2;
// Update max distance
maxDist = max(maxDist, vert + hori);
}
return maxDist;
}
};
publicclassSolution {
publicintmaxDistance(String s, int k) {
int maxDist = 0;
int north = 0, south = 0, east = 0, west = 0;
for (char ch : s.toCharArray()) {
// Update direction counters based on the current characterswitch (ch) {
case'N': north++; break;
case'S': south++; break;
case'E': east++; break;
case'W': west++; break;
}
// Determine how many changes can be applied to vertical directionsint vertChanges = Math.min(Math.min(north, south), k);
// Use remaining changes for horizontal directionsint horiChanges = Math.min(Math.min(east, west), k - vertChanges);
// Update the maximum distance found so far maxDist = Math.max(
maxDist,
calcDist(north, south, vertChanges) + calcDist(east, west, horiChanges)
);
}
return maxDist;
}
// Compute the Manhattan distance for a pair of directions after applying modificationsprivateintcalcDist(int dir1, int dir2, int changes) {
return Math.abs(dir1 - dir2) + changes * 2;
}
}
classSolution:
defmaxDistance(self, s: str, k: int) -> int:
north = south = east = west =0 max_dist =0for ch in s:
if ch =='N':
north +=1elif ch =='S':
south +=1elif ch =='E':
east +=1elif ch =='W':
west +=1 vert = abs(north - south)
hori = abs(east - west)
rem_k = k
vert_change = min(rem_k, min(north, south))
vert += vert_change *2 rem_k -= vert_change
hori_change = min(rem_k, min(east, west))
hori += hori_change *2 max_dist = max(max_dist, vert + hori)
return max_dist