2025-06-20 Daily Challenge

Today I have done leetcode's June LeetCoding Challenge with cpp.

June LeetCoding Challenge 20

Description

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:

Input: s = "NWSE", k = 1

Output: 3

Explanation:

Change s[2] from 'S' to 'N'. The string s becomes "NWNE".

Movement Position (x, y) Manhattan Distance Maximum
s[0] == 'N' (0, 1) 0 + 1 = 1 1
s[1] == 'W' (-1, 1) 1 + 1 = 2 2
s[2] == 'N' (-1, 2) 1 + 2 = 3 3
s[3] == 'E' (0, 2) 0 + 2 = 2 3

The maximum Manhattan distance from the origin that can be achieved is 3. Hence, 3 is the output.

Example 2:

Input: s = "NSWWEW", k = 3

Output: 6

Explanation:

Change s[1] from 'S' to 'N', and s[4] from 'E' to 'W'. The string s becomes "NNWWWW".

The maximum Manhattan distance from the origin that can be achieved is 6. Hence, 6 is the output.

 

Constraints:

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

Solution

class Solution {
  static map<char, int> directToIndex;
public:
  int maxDistance(string s, int k) {
    vector<int> count(4);
    int answer = 0;
    for(auto d : s) {
      count[directToIndex[d]] += 1;
      int change1 = min({count[0], count[1], k});
      int change2 = min({count[2], count[3], k - change1});
      answer = max(answer, abs(count[0] - count[1]) + abs(count[2] - count[3]) + 2 * (change1 + change2));
    }
    return answer;
  }
};
map<char, int> Solution::directToIndex = map<char, int>{
  {'W', 0},
  {'E', 1},
  {'N', 2},
  {'S', 3}
};

// Accepted
// 828/828 cases passed (181 ms)
// Your runtime beats 44.24 % of cpp submissions
// Your memory usage beats 52.12 % of cpp submissions (38.5 MB)