[C++] Single Pass, Greedy
Complexity
Time complexity: O(n)
Space complexity: O(1)
Code
# Complexity
- Time complexity: $$O(n)$$
- Space complexity: $$O(1)$$

# Code
```cpp []
class Solution {
public:
    int maxDistance(string s, int k) {
        int maximum_distance = 0;
        int north = 0, west = 0, south = 0, east = 0;
        for (const auto& c : s) {
            if (c == 'N')
                north++;
            if (c == 'W')
                west++;
            if (c == 'S')
                south++;
            if (c == 'E')
                east++;
            int changes = k;
            int north_south_offset = min(min(north, south), changes);
            changes -= north_south_offset;
            int east_west_offset = min(min(east, west), changes);
            int distance = abs(north - south) + 2 * north_south_offset + abs(west - east) + 2 * east_west_offset;
            maximum_distance = max(maximum_distance, distance);
        }
        return maximum_distance;
    }
};
```
['Greedy', 'Counting', 'C++']