Java || Very Easy || Net Movement + 2 * min(opposite, k)🔥|| Clean code
ApproachWe count occurrences of each movement ('N', 'S', 'E', 'W'). The net displacement in the x and y directions is given by:netX = East count − West count
ne

# Approach

We count occurrences of each movement ('N', 'S', 'E', 'W'). The net displacement in the x and y directions is given by:  

netX = East count − West count
netY = North count − South count

The initial Manhattan distance is:

distance = |netX| + |netY|


Since we can change at most \( k \) characters, we maximize the distance by converting up to \( k \) movements to further increase the displacement in one direction. We consider four possible directions and take the maximum:  

1. Maximizing  (N + E) - (S + W)  
2. Maximizing (N + W) - (S + E) 
3. Maximizing  (S + E) - (N + W) 
4. Maximizing (S + W) - (N + E) 

For each case, we add ( 2 * min(opposite moves, k) to shift movements optimally. The answer is the maximum possible distance across these cases.

## Why this formula [Net Movement + 2 * min(opposite, k)]

We can think greedily: If we have 5N and 3S, and suppose \( k > 10 \), converting (S → N) would ideally increase net movement by 3. However, it actually increases by twice this amount (i.e., \( 2 * 3 \), because initially, the net movement was 3 units south, and after converting S → N, the net movement shifts 6 units north.

# Complexity
- Time complexity:
O(n)

- Space complexity:
O(1)

# Code
```java []
class Solution {
    public int maxDistance(String st, int k) {
        
        int n = 0, s = 0, e = 0, w = 0;
        int max = 0;
       
        for (char c : st.toCharArray()) {
            if (c == 'N') {
                n++;
            } else if (c == 'S') {
                s++;
            } else if (c == 'E') {
                e++;
            } else {
                w++;
            }
            max = Math.max(max, n + e - w - s + 2 * Math.min(s + w, k));
            max = Math.max(max, n + w - s - e + 2 * Math.min(s + e, k));
            max = Math.max(max, s + e - n - w + 2 * Math.min(n + w, k));
            max = Math.max(max, s + w - n - e + 2 * Math.min(n + e, k));
        }

        return max;
    }
}

```
['Java']