Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created June 20, 2025 16:41
Show Gist options
  • Save tatsuyax25/d9527d466da37fee8065b5064f638834 to your computer and use it in GitHub Desktop.
Save tatsuyax25/d9527d466da37fee8065b5064f638834 to your computer and use it in GitHub Desktop.
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
/**
* Calculates the maximum Manhattan distance from the origin
* that can be achieved while moving in a grid, with the option
* to change up to 'k' directions.
*
* @param {string} s - String of movement directions: 'N', 'S', 'E', 'W'.
* @param {number} k - Number of allowed direction changes.
* @return {number} - Maximum distance from the origin at any point.
*/
var maxDistance = function(s, k) {
let x = 0, y = 0; // Current coordinates on the grid
let maxDist = 0; // Tracks the farthest distance from origin
for (let i = 0; i < s.length; i++) {
const ch = s[i];
// Update coordinates based on current move
if (ch === 'N') y += 1;
else if (ch === 'S') y -= 1;
else if (ch === 'E') x += 1;
else if (ch === 'W') x -= 1;
// At most k changes allowed, but we can’t change more than i + 1 steps so far
const changes = Math.min(k, i + 1);
// Each change can increase distance by up to 2 units (reversing direction fully)
const maxPossibleDist = Math.abs(x) + Math.abs(y) + 2 * changes;
// Cap the distance by the total number of steps taken so far
const cappedDist = Math.min(maxPossibleDist, i + 1);
maxDist = Math.max(maxDist, cappedDist);
}
return maxDist;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment