# Furthest From Origin in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

Suppose we have a string s where each character is either "L", "R" or "?". "L" means moved one unit left, "R" means moved one unit right, and "?" means either "L" or "R". If we are at position 0, we have to find the maximum possible distance we could be from 0 by replacing "?" with "L" or "R".

So, if the input is like "LLRRL??", then the output will be 3, replace ? using L to move 5 units left and 2 units right, so maximum displacement is 3.

To solve this, we will follow these steps −

• op := 0, l := 0, r := 0

• for each it in s −

• if it is same as 'L', then −

• (increase l by 1)

• otherwise when it is same as 'R', then −

• (increase r by 1)

• Otherwise

• (increase op by 1)

• return maximum of (l and r) - minimum of (l and r) + op

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int solve(string s) {
int op = 0;
int l = 0;
int r = 0;
for (auto &it : s) {
if (it == 'L') {
l++;
} else if (it == 'R') {
r++;
} else {
op++;
}
}
return max(l, r) - min(l, r) + op;
}
};
main() {
Solution ob;
cout << (ob.solve("LLRRL??"));
}

## Input

"LLRRL??"

## Output

3
Updated on 02-Sep-2020 11:38:02