[LeetCode] Maximum Manhattan Distance After K Changes

3443. Maximum Manhattan Distance After K Changes

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|.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main


func helper(A, B [2]int, k int) int {
mia := min(A[0], k)
A[0] -= mia
k -= mia
B[1] += mia

mib := min(B[0], k)
B[0] -= mib
k -= mib
A[1] += mib

return A[1] - A[0] + B[1] - B[0]
}

func helper2(ns, ew [2]int, k int) int {
if ns[0] > ns[1] {
ns[0], ns[1] = ns[1], ns[0]
}
if ew[0] > ew[1] {
ew[0], ew[1] = ew[1], ew[0]
}
return max(helper(ns, ew, k), helper(ew, ns, k))
}

func maxDistance(s string, k int) int {
ns := [2]int{0, 0}
ew := [2]int{0, 0}
res := 0

for _, ch := range s {
if ch == 'N' {
ns[0]++
}
if ch == 'S' {
ns[1]++
}
if ch == 'E' {
ew[0]++
}
if ch == 'W' {
ew[1]++
}
res = max(res, helper2(ns, ew, k))
}

return res
}

func max(a, b int) int {
if a > b {
return a
}
return b
}

func min(a, b int) int {
if a < b {
return a
}
return b
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/02/02/PS/LeetCode/maximum-manhattan-distance-after-k-changes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.