Maximum Manhattan Distance After K Changes Problem
Description
LeetCode Problem 3443.
You are given a string s consisting of the characters 'N', 'S', 'E', and 'W', where s[i] indicates movements in an infinite grid:
'N': Move north by 1 unit.'S': Move south by 1 unit.'E': Move east by 1 unit.'W': Move west by 1 unit.
Initially, you are at the origin (0, 0). You can change at most k characters to any of the four directions.
Find the maximum Manhattan distance from the origin that can be achieved at any time while performing the movements in order.
The Manhattan Distance between two cells (x_i, y_i) and (x_j, y_j) is |x_i - x_j| + |y_i - y_j|.
Example 1:
Input: s = "NWSE", k = 1
Output: 3
Explanation:
Change s[2] from 'S' to 'N'. The string s becomes "NWNE".
Movement Position (x, y) Manhattan Distance Maximum
s[0] == 'N' (0, 1) 0 + 1 = 1 1
s[1] == 'W' (-1, 1) 1 + 1 = 2 2
s[2] == 'N' (-1, 2) 1 + 2 = 3 3
s[3] == 'E' (0, 2) 0 + 2 = 2 3
The maximum Manhattan distance from the origin that can be achieved is 3. Hence, 3 is the output.
Example 2:
Input: s = "NSWWEW", k = 3
Output: 6
Explanation:
Change s[1] from 'S' to 'N', and s[4] from 'E' to 'W'. The string s becomes "NNWWWW".
The maximum Manhattan distance from the origin that can be achieved is 6. Hence, 6 is the output.
Constraints:
1 <= s.length <= 10^50 <= k <= s.lengthsconsists of only'N','S','E', and'W'.
Solution
Approach: Enumeration and Greedy
The final point is farthest from the origin in one of four diagonal directions: south-east, south-west, north-east or north-west. For each pair, say calc(a, b), walk along s:
- A move equal to
aorbincreases the distance by one. - Any other move is flipped to
aorbwhile we still have changes left (cnt < k), which also increases the distance by one. - Otherwise the move decreases the distance by one.
Record the maximum distance seen after each step, since we can stop at any prefix. The answer is the maximum over the four pairs.
Complexity: O(n) time and O(1) space.
class Solution:
def maxDistance(self, s: str, k: int) -> int:
def calc(a: str, b: str) -> int:
ans = mx = cnt = 0
for c in s:
if c == a or c == b:
mx += 1
elif cnt < k:
cnt += 1
mx += 1
else:
mx -= 1
ans = max(ans, mx)
return ans
a = calc("S", "E")
b = calc("S", "W")
c = calc("N", "E")
d = calc("N", "W")
return max(a, b, c, d)