Maximum Manhattan Distance After K Changes - Problem

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

example_1.py — Basic Example
$ Input: s = "NESE", k = 1
Output: 4
💡 Note: Original path: (0,0)→(0,1)→(1,1)→(1,0)→(2,0), max distance = 2. Change S to N: (0,0)→(0,1)→(1,1)→(1,2)→(2,2), max distance = 4.
example_2.py — Multiple Changes
$ Input: s = "NSEW", k = 2
Output: 4
💡 Note: Original path reaches max distance 1. Change N→E and S→E to get "EEEW": (0,0)→(1,0)→(2,0)→(3,0)→(2,0), max distance = 3. Better: change N→E and W→E to get "ESEE": (0,0)→(1,0)→(1,-1)→(2,-1)→(3,-1), max distance = 4.
example_3.py — No Changes Needed
$ Input: s = "NNNN", k = 0
Output: 4
💡 Note: Already optimal path going straight North: (0,0)→(0,1)→(0,2)→(0,3)→(0,4), max distance = 4.

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

Visualization

Tap to expand
Maximum Manhattan Distance After K Changes INPUT (0,0) N (+y) S (-y) E (+x) W (-x) String s: N E S E k = 1 (changes) ALGORITHM (Greedy) 1 Track position Process each move, track max distance 2 Greedy change Change S to N when k allows, maximize y 3 Calculate distance |x| + |y| at each step 4 Return maximum Best distance found Trace (with k=1 change): Step Move Pos Dist 0 - (0,0) 0 1 N (0,1) 1 2 E (1,1) 2 3 S--N (1,2) 3 4 E (2,2) 4 [MAX] FINAL RESULT x y (0,0) (2,2) Original move Changed move OUTPUT 4 Key Insight: Greedy approach: At each step, use available changes to maximize distance from origin. Change opposing moves (S to N, or W to E) to push further in the dominant direction. Track maximum Manhattan distance |x| + |y| reached at ANY point during the journey. TutorialsPoint - Maximum Manhattan Distance After K Changes | Greedy Approach
Asked in
Google 42 Meta 35 Amazon 28 Microsoft 22
47.2K Views
Medium Frequency
~25 min Avg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen