diff --git a/solution/3400-3499/3443.Maximum Manhattan Distance After K Changes/README.md b/solution/3400-3499/3443.Maximum Manhattan Distance After K Changes/README.md index 4537839137315..6138b49fb8e1d 100644 --- a/solution/3400-3499/3443.Maximum Manhattan Distance After K Changes/README.md +++ b/solution/3400-3499/3443.Maximum Manhattan Distance After K Changes/README.md @@ -279,6 +279,38 @@ function maxDistance(s: string, k: number): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn max_distance(s: String, k: i32) -> i32 { + fn calc(s: &str, a: char, b: char, k: i32) -> i32 { + let mut ans = 0; + let mut mx = 0; + let mut cnt = 0; + for c in s.chars() { + if c == a || c == b { + mx += 1; + } else if cnt < k { + mx += 1; + cnt += 1; + } else { + mx -= 1; + } + ans = ans.max(mx); + } + ans + } + + let a = calc(&s, 'S', 'E', k); + let b = calc(&s, 'S', 'W', k); + let c = calc(&s, 'N', 'E', k); + let d = calc(&s, 'N', 'W', k); + a.max(b).max(c).max(d) + } +} +``` + diff --git a/solution/3400-3499/3443.Maximum Manhattan Distance After K Changes/README_EN.md b/solution/3400-3499/3443.Maximum Manhattan Distance After K Changes/README_EN.md index 0a45d26e2eb76..713ebf21d5b78 100644 --- a/solution/3400-3499/3443.Maximum Manhattan Distance After K Changes/README_EN.md +++ b/solution/3400-3499/3443.Maximum Manhattan Distance After K Changes/README_EN.md @@ -275,6 +275,38 @@ function maxDistance(s: string, k: number): number { } ``` +#### Rust + +```rust +impl Solution { + pub fn max_distance(s: String, k: i32) -> i32 { + fn calc(s: &str, a: char, b: char, k: i32) -> i32 { + let mut ans = 0; + let mut mx = 0; + let mut cnt = 0; + for c in s.chars() { + if c == a || c == b { + mx += 1; + } else if cnt < k { + mx += 1; + cnt += 1; + } else { + mx -= 1; + } + ans = ans.max(mx); + } + ans + } + + let a = calc(&s, 'S', 'E', k); + let b = calc(&s, 'S', 'W', k); + let c = calc(&s, 'N', 'E', k); + let d = calc(&s, 'N', 'W', k); + a.max(b).max(c).max(d) + } +} +``` + diff --git a/solution/3400-3499/3443.Maximum Manhattan Distance After K Changes/Solution.rs b/solution/3400-3499/3443.Maximum Manhattan Distance After K Changes/Solution.rs new file mode 100644 index 0000000000000..901f6a1003b53 --- /dev/null +++ b/solution/3400-3499/3443.Maximum Manhattan Distance After K Changes/Solution.rs @@ -0,0 +1,27 @@ +impl Solution { + pub fn max_distance(s: String, k: i32) -> i32 { + fn calc(s: &str, a: char, b: char, k: i32) -> i32 { + let mut ans = 0; + let mut mx = 0; + let mut cnt = 0; + for c in s.chars() { + if c == a || c == b { + mx += 1; + } else if cnt < k { + mx += 1; + cnt += 1; + } else { + mx -= 1; + } + ans = ans.max(mx); + } + ans + } + + let a = calc(&s, 'S', 'E', k); + let b = calc(&s, 'S', 'W', k); + let c = calc(&s, 'N', 'E', k); + let d = calc(&s, 'N', 'W', k); + a.max(b).max(c).max(d) + } +}