Intuition
Each '_' independently picks 'L' or 'R'. With k underscores there are 2^k strings; for each one compute the position and take the max absolute value.
Explanation
Approach
- Enumerate every assignment of
'L'/'R'to thekunderscore positions (recursive backtracking). - For each fully-assigned string, compute
count('R') - count('L'). - Track the maximum absolute value.
Complexity
- Time:
O(2^k · n)— exponential in the underscores. - Space:
O(n)— recursion stack and string buffer.
Implementation
class Solution {
private int best = 0;
public int furthestDistanceFromOrigin(String moves) {
best = 0;
backtrack(moves, 0, 0);
return best;
}
private void backtrack(String moves, int i, int pos) {
if (i == moves.length()) {
best = Math.max(best, Math.abs(pos));
return;
}
char c = moves.charAt(i);
if (c == 'L') {
backtrack(moves, i + 1, pos - 1);
} else if (c == 'R') {
backtrack(moves, i + 1, pos + 1);
} else {
backtrack(moves, i + 1, pos - 1);
backtrack(moves, i + 1, pos + 1);
}
}
}