#3443
Medium Algorithms Maximum manhattan distance after k changes
Hash Table Math String Counting
54.2% acceptance
Feb 25, 2026
600
69
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|.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn max_distance(s: String, k: i32) -> i32 {
// At each step i, we have moved in 4 directions. We can change k of them.
// After i steps with counts N,S,E,W:
// x = E - W, y = N - S, |x|+|y| = Manhattan dist
// Changing up to k moves: we can increase |x|+|y| by at most 2*k (redirect k opposing to aligned)
// Max Manhattan = |x| + |y| + 2*min(k, complementary)
// More carefully: with i total moves, max Manhattan with k changes = min(i, |x|+|y| + 2*k)
let mut n = 0i32; let mut s_cnt = 0i32; let mut e = 0i32; let mut w = 0i32;
let mut ans = 0i32;
let k = k as i32;
for c in s.bytes() {
match c { b'N' => n += 1, b'S' => s_cnt += 1, b'E' => e += 1, _ => w += 1 }
let steps = (n + s_cnt + e + w) as i32;
let x = (e - w).abs();
let y = (n - s_cnt).abs();
let dist = (x + y + 2 * k).min(steps);
if dist > ans { ans = dist; }
}
ans
}
}