Easy 5 Step Simple Code Explained
🎯 Approach
Step 1: Count the number of number of movements towards north, south , east and west.
Step 2: Using m to check that we don't make more changes than p
# 🎯 Approach

- **Step 1:** Count the number of number of movements towards `north`, `south` , `east` and `west`.
- **Step 2:** Using `m` to check that we don't make more changes than possible for the given length eg -> (we don't make `5` changes when length is `4`)
- **Step 3:** We then consider `4` cases as listed in the code below of all possible ways that the manhattan distance could be the maximum.
- **Step 4:** We then lastly use `maxi` take the best one out of these `4` cases.
- **Step 5:** Finally we check whether `maxi` is better than the    `initial` state of the string and store `maxi` in the `result` if its a better way to make swaps i.e it has a larger value than `result`.

---
# 🔥 Implementation
```cpp []
class Solution {
public:
    int maxDistance(string s, int k) {
        int north = 0, south = 0, east = 0, west = 0, result = 0;
        for (int i = 0; i < s.size(); i++) {
            if(s[i] =='N') north++;
            else if(s[i] =='S') south++;
            else if(s[i] =='E') east++;
            else if(s[i] =='W') west++;
            int j = i + 1;
            int m = min(k, j);
            // when east > west , north > south
            int case1 = (east - west + north - south) + 2 * min(m, west + south); 
            // when west > east , north > south
            int case2 = (west - east + north - south) + 2 * min(m, east + south); 
            // when east > west , south > north
            int case3 = (east - west + south - north) + 2 * min(m, west + north);
            // when west > east , south > north
            int case4 = (west - east + south - north) + 2 * min(m, east + north); 

            int maxi = max({case1, case2, case3, case4}); // best case
            maxi = min(maxi, j); // Making sure we aren't making more than k swaps

            // Checking if its better than initial case
            int initial = abs(east - west) + abs(north - south); 
            maxi = max(maxi, initial);
            result = max(result, maxi);
        }
        return result;
    }
};
```
['C++']