Leetcode 2833. Furthest Point From Origin
Given a string moves
that represents the movement instructions of a character starting at the origin (0,0)
on a 2D plane, return the maximum distance the character can be from the origin after executing the given moves.
The string moves
consists of characters 'L'
(left), 'R'
(right), or '_'
(either left or right).
_
character be replaced by either L
or R
to maximize the distance from the origin?
'_ '
can be replaced with either 'L'
or 'R'
.moves
?
'L'
, 'R'
, or '_'
.To maximize the distance from the origin, we need to understand the effect of each character:
'L'
moves the character 1 unit left (towards the negative x-axis).'R'
moves the character 1 unit right (towards the positive x-axis).'_ '
can move the character either left or right. To maximize the distance, each '_ '
should move in the direction that currently increases the net displacement further.The steps are:
'L'
and 'R'
moves.'_ '
moves to the absolute value of this net displacement to maximize it.public class Solution {
public int furthestDistanceFromOrigin(String moves) {
int leftCount = 0;
int rightCount = 0;
int underscoreCount = 0;
for (char move : moves.toCharArray()) {
if (move == 'L') {
leftCount++;
} else if (move == 'R') {
rightCount++;
} else {
underscoreCount++;
}
}
int netDisplacement = Math.abs(leftCount - rightCount);
return netDisplacement + underscoreCount;
}
}
leftCount
, rightCount
, and underscoreCount
, to 0.moves
string and increment the counters based on whether the character is 'L'
, 'R'
, or '_'
.Math.abs(leftCount - rightCount)
.The time complexity of this solution is O(n), where n is the length of the string moves
. We traverse the string once to count each type of move, making the solution efficient and optimal for large inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?