Imagine you're controlling a robot on an infinite grid, starting at the origin (0, 0). You have a sequence of movement commands represented by a string s where each character tells the robot which direction to move:
- 'N': Move north (up) by 1 unit
- 'S': Move south (down) by 1 unit
- 'E': Move east (right) by 1 unit
- 'W': Move west (left) by 1 unit
Here's the twist: before executing the movement sequence, you can modify at most k characters in the string to any of the four directions. Your goal is to maximize the Manhattan distance from the origin that the robot reaches at any point during its journey.
The Manhattan distance between two points (x₁, y₁) and (x₂, y₂) is |x₁ - x₂| + |y₁ - y₂|.
Key insight: You want to strategically change some moves to make the robot travel as far as possible from the origin at some point during its path, not necessarily at the end.
Input & Output
Visualization
Time & Space Complexity
O(n) to calculate prefix sums, O(n log n) to sort potential improvements
Space for storing prefix sums and improvement candidates
Constraints
- 1 ≤ s.length ≤ 105
- 0 ≤ k ≤ s.length
- s consists only of characters 'N', 'S', 'E', 'W'
- The string represents a valid sequence of moves