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

Example 1
Inputs = "NWSE", k = 1
Output3
Changing s[2] from 'S' to 'N' makes s become "NWNE", whose maximum Manhattan distance from the origin is 3.
Example 2
Inputs = "NSWWEW", k = 3
Output6
Changing s[1] from 'S' to 'N' and s[4] from 'E' to 'W' makes s become "NNWWWW", whose maximum Manhattan distance from the origin is 6.

Constraints

  • 1 <= s.length <= 10^5
  • 0 <= k <= s.length
  • s consists of only 'N', 'S', 'E', and 'W'.

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate