3443. Maximum Manhattan Distance After K Changes
Description
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 (xi, yi)
and (xj, yj)
is |xi - xj| + |yi - yj|
.
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 <= 105
0 <= k <= s.length
s
consists of only'N'
,'S'
,'E'
, and'W'
.
Solutions
Solution 1: Enumeration + Greedy
We can enumerate four cases: \(\textit{SE}\), \(\textit{SW}\), \(\textit{NE}\), and \(\textit{NW}\), and then calculate the maximum Manhattan distance for each case.
We define a function \(\text{calc}(a, b)\) to calculate the maximum Manhattan distance when the effective directions are \(\textit{a}\) and \(\textit{b}\).
We define a variable \(\textit{mx}\) to record the current Manhattan distance, a variable \(\textit{cnt}\) to record the number of changes made, and initialize the answer \(\textit{ans}\) to \(0\).
Traverse the string \(\textit{s}\). If the current character is \(\textit{a}\) or \(\textit{b}\), increment \(\textit{mx}\) by \(1\). Otherwise, if \(\textit{cnt} < k\), increment \(\textit{mx}\) by \(1\) and increment \(\textit{cnt}\) by \(1\). Otherwise, decrement \(\textit{mx}\) by \(1\). Then update \(\textit{ans} = \max(\textit{ans}, \textit{mx})\).
Finally, return the maximum value among the four cases.
The time complexity is \(O(n)\), where \(n\) is the length of the string \(\textit{s}\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|