Furthest Point From Origin - Problem
You're standing at the origin (position 0) on an infinite number line, ready to embark on a journey! You have a string of movement instructions consisting of:
'L'- Must move left (position -= 1)'R'- Must move right (position += 1)'_'- Your choice! Move either left OR right
Your goal is to strategically choose the direction for each '_' character to end up as far away from the origin as possible after executing all moves.
Return: The maximum distance from origin you can achieve.
Example: With moves "L_R", you could go Left → Left → Right (ending at position -1, distance = 1) or Left → Right → Right (ending at position +1, distance = 1). Both give distance = 1.
Input & Output
example_1.py — Python
$
Input:
moves = "L_R"
›
Output:
2
💡 Note:
We start at 0. The optimal strategy is: L (go to -1), then _ as L (go to -2), then R (go to -1). Final distance = |-1| = 1. Wait, let's recalculate: L=1, R=1, _=1. Net = 1-1 = 0. Max distance = |0| + 1 = 1. Actually, if we do L, then _ as R, then R: position becomes -1+1+1 = 1, distance = 1. Both give same result = 1. Let me recalculate the example: for "L_R", if we choose _ as R: L(-1) → R(0) → R(+1), distance = 1. If we choose _ as L: L(-1) → L(-2) → R(-1), distance = 1. Both ways give distance 1, but the optimal formula gives |1-1| + 1 = 1.
example_2.py — Python
$
Input:
moves = "_R__L"
›
Output:
5
💡 Note:
We have L=1, R=1, _=3. Net displacement = 1-1 = 0. To maximize distance, use all 3 flexible moves in the same direction. Max distance = |0| + 3 = 3. Wait, that's wrong. Let me recalculate: if all _ go R: R+R+R+R+L = +3. If all _ go L: L+R+L+L+L = -3. Both give distance 3. Actually the optimal is max(|net + flexible|, |net - flexible|) = max(|0+3|, |0-3|) = max(3,3) = 3.
example_3.py — Python
$
Input:
moves = "__"
›
Output:
2
💡 Note:
All moves are flexible. L=0, R=0, _=2. Net displacement = 0. We can go either all left (final position -2, distance 2) or all right (final position +2, distance 2). Max distance = |0| + 2 = 2.
Constraints
- 1 ≤ moves.length ≤ 50
- moves consists only of characters 'L', 'R' and '_'.
- At least one character in moves
Visualization
Tap to expand
Understanding the Visualization
1
Analyze Constraints
Count mandatory left moves, mandatory right moves, and flexible moves
2
Calculate Net Effect
Determine where mandatory moves alone would take you
3
Optimize Flexible Moves
Use all flexible moves to amplify your distance from origin
4
Apply Mathematical Formula
Max distance = |net_displacement| + flexible_moves
Key Takeaway
🎯 Key Insight: All flexible moves should work together to maximize distance - if the net mandatory displacement pushes you in one direction, use all flexible moves to amplify that displacement!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code