3443. Maximum Manhattan Distance After K Changes #1830
-
Topics: You are given a string
Initially, you are at the origin Find the maximum Manhattan distance from the origin that can be achieved at any time while performing the movements in order. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum Manhattan distance from the origin (0, 0) achievable at any point during the sequence of movements, given that we can change at most Approach
Let's implement this solution in PHP: 3443. Maximum Manhattan Distance After K Changes <?php
/**
* @param String $s
* @param Integer $k
* @return Integer
*/
function maxDistance($s, $k) {
$x = 0;
$y = 0;
$ans = 0;
$n = strlen($s);
for ($i = 0; $i < $n; $i++) {
$char = $s[$i];
if ($char == 'N') {
$y++;
} elseif ($char == 'S') {
$y--;
} elseif ($char == 'E') {
$x++;
} elseif ($char == 'W') {
$x--;
}
$current = abs($x) + abs($y);
$c = min($i + 1, $k);
$candidate = $current + 2 * $c;
$best_at_i = min($i + 1, $candidate);
if ($best_at_i > $ans) {
$ans = $best_at_i;
}
}
return $ans;
}
// Test cases
echo maxDistance("NWSE", 1) . PHP_EOL; // 3
echo maxDistance("NSWWEW", 3) . PHP_EOL; // 6
?> Explanation:
This approach efficiently computes the maximum Manhattan distance by leveraging the observation that each change can contribute up to 2 units to the distance, while ensuring the solution remains within feasible bounds by considering the number of movements processed. The algorithm runs in linear time, O(n), where n is the length of the string, making it suitable for large inputs. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum Manhattan distance from the origin (0, 0) achievable at any point during the sequence of movements, given that we can change at most
k
characters in the strings
to any of the four directions ('N', 'S', 'E', 'W'). The Manhattan distance is defined as the sum of the absolute differences in the x and y coordinates, i.e., |x| + |y|.Approach
ans
).