Easiest solution for this problem - using single O(n) loop
Intuitionsimply count all four chars, if we have n and s or e and w both they will cancel each other.
and we need to calculate ans on every step.Approachsee the
# Intuition
simply count all four chars, if we have n and s or e and w both they will cancel each other.
and we need to calculate ans on every step.
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach
see the solution its very obvious
<!-- Describe your approach to solving the problem. -->

# Complexity
- Time complexity: O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity: O(1) - during i created ans vector but there is no need of that array we can also use 1 ans variable.
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```cpp []
class Solution {
public:
    int maxDistance(string str, int k) {
        vector<int> ans;
        int n = 0;
        int w = 0;
        int s = 0;
        int e = 0;
        
        for(char c : str){
            if(c=='N'){
                n++;
            }else if(c=='W'){
                w++;
            }else if(c=='S'){
                s++;
            }else{
                e++;
            }
            int ma = max(n, s);
            int mi = min(n, s);
            int maa = max(w, e);
            int mii = min(w, e);
            int p = min(mi+mii, k);
            ans.push_back(ma + maa -mi -mii + 2*p);
            
        }
        int res = 0;
        for(int i : ans){
            res = max(res, i);
        }
        return res;
        
    }
};
```
['C++']