
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Furthest From Origin in C++
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
#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
- Related Articles
- Robot Return to Origin in C++
- Find K Closest Points to the Origin in C++
- Check if a line passes through the origin in C++
- How to plot the regression line starting from origin using ggplot2 in R?
- Find the distance of the point $( 6,\ -8)$ from the origin.
- Cross-origin data in HTML5 Canvas
- What is text origin in JavaFX?
- Find the distance of a point $R( -6,\ -8)$ from the origin.
- Find the distance of a point $P( x,\ y)$ from the origin.
- CSS perspective-origin property
- CSS background-origin property
- Biochemical Origin of Life
- What evidence do we have for the origin of life from inanimate matter?
- Finding points nearest to origin in JavaScript
- HTML DOM Anchor origin Property
