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.
Maximum Manhattan Distance After K Changes — Solution
The optimal solution uses prefix sums to efficiently track the robot's position after each move, then applies a greedy strategy to identify which moves to change for maximum distance improvement. Key insight: calculate the improvement each potential change would provide and select the top k changes that maximize the Manhattan distance reached at any point during the journey.
Common Approaches
✓
Optimized
⏱️ Time: N/A
Space: N/A
Math
⏱️ Time: N/A
Space: N/A
Brute Force (Try All Combinations)
⏱️ Time: O(C(n,k) * 4^k * n)
Space: O(n)
Generate all possible ways to change at most k characters in the string, then for each possibility, simulate the entire path and track the maximum Manhattan distance achieved at any point.
Prefix Sum + Greedy (Optimal)
⏱️ Time: O(n log n)
Space: O(n)
Calculate prefix sums to determine the robot's position after each move. Then use a greedy approach to identify which moves to change to maximize the Manhattan distance at any point during the journey.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static int combinations[10000][20];
static int combination_sizes[10000];
static int num_combinations = 0;
static char products[100000][20];
static int num_products = 0;
int manhattan_distance(int x, int y) {
return (x < 0 ? -x : x) + (y < 0 ? -y : y);
}
int simulate_path(char* moves, int len) {
int x = 0, y = 0;
int max_dist = 0;
for (int i = 0; i < len; i++) {
if (moves[i] == 'N') {
y += 1;
} else if (moves[i] == 'S') {
y -= 1;
} else if (moves[i] == 'E') {
x += 1;
} else if (moves[i] == 'W') {
x -= 1;
}
int dist = manhattan_distance(x, y);
if (dist > max_dist) {
max_dist = dist;
}
}
return max_dist;
}
void get_combinations(int* current, int current_size, int start, int n, int k) {
if (current_size == k) {
for (int i = 0; i < k; i++) {
combinations[num_combinations][i] = current[i];
}
combination_sizes[num_combinations] = k;
num_combinations++;
return;
}
for (int i = start; i < n; i++) {
current[current_size] = i;
get_combinations(current, current_size + 1, i + 1, n, k);
}
}
void get_cartesian_product(char* current, int current_size, char* directions, int remaining) {
if (remaining == 0) {
for (int i = 0; i < current_size; i++) {
products[num_products][i] = current[i];
}
products[num_products][current_size] = '\0';
num_products++;
return;
}
for (int i = 0; i < 4; i++) {
current[current_size] = directions[i];
get_cartesian_product(current, current_size + 1, directions, remaining - 1);
}
}
int solution(char* s, int k) {
int n = strlen(s);
char directions[] = {'N', 'S', 'E', 'W'};
int max_distance = simulate_path(s, n);
if (k == 0) {
return max_distance;
}
int min_val = (k < n) ? k : n;
// Get combinations
num_combinations = 0;
int current[20];
get_combinations(current, 0, 0, n, min_val);
for (int combo = 0; combo < num_combinations; combo++) {
// Get cartesian product for this combination
num_products = 0;
char current_product[20];
get_cartesian_product(current_product, 0, directions, combination_sizes[combo]);
for (int prod = 0; prod < num_products; prod++) {
char modified_moves[100];
strcpy(modified_moves, s);
for (int i = 0; i < combination_sizes[combo]; i++) {
modified_moves[combinations[combo][i]] = products[prod][i];
}
int dist = simulate_path(modified_moves, n);
if (dist > max_distance) {
max_distance = dist;
}
}
}
return max_distance;
}
int main() {
char s[100];
int k;
scanf("%s", s);
scanf("%d", &k);
int result = solution(s, k);
printf("%d\n", result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
n
2n
⚡ Linearithmic Space
47.2K Views
MediumFrequency
~25 minAvg. Time
1.3K Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.