Leetcode 2833. Furthest Point From Origin
You’re given a string moves
consisting of characters 'L'
, 'R'
, and '_'
. Each character represents a move along a straight line:
'L'
: Move one step to the left.'R'
: Move one step to the right.'_'
: Move can either be 'L'
or 'R'
.Your task is to determine the maximum possible distance from the origin after all the moves in the string moves
.
moves
contains at least one character.moves
?
10^5
characters, but this will be coded in a generic way without assuming a specific limit.moves
are sequential moves to be followed accordingly.left_moves
: Count of movements to the left 'L'
.right_moves
: Count of movements to the right 'R'
.neutral_moves
: Count of movements which can be either 'L'
or 'R'
denoted by '_'
.left_moves + neutral_moves - right_moves
.right_moves + neutral_moves - left_moves
.left_moves
, right_moves
, and neutral_moves
.#include <iostream>
#include <string>
#include <cmath>
int furthestPointFromOrigin(const std::string &moves) {
int left_moves = 0, right_moves = 0, neutral_moves = 0;
for (char move : moves) {
if (move == 'L') left_moves++;
else if (move == 'R') right_moves++;
else if (move == '_') neutral_moves++;
}
int max_distance = std::max(left_moves + neutral_moves - right_moves, right_moves + neutral_moves - left_moves);
return max_distance;
}
int main() {
std::string moves = "L__R_RL";
std::cout << "Furthest Point From Origin: " << furthestPointFromOrigin(moves) << std::endl;
return 0;
}
Time Complexity: The time complexity of this solution is (O(n)), where (n) is the length of the string moves
. This is because we iterate through the string once to count the moves.
Space Complexity: The space complexity is (O(1)) because we use a fixed amount of space for counting the moves (left_moves
, right_moves
, neutral_moves
).
This approach effectively counts the different types of moves and computes the maximum possible distance from the origin by considering all possible choices for neutral moves.
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?