Given the maximum occurrences of a, b, and c in a string, the task is to make the string containing only a, b, and c such that no three consecutive characters are the same. If the resultant string equals a+b+c, return the length (a+b+c) otherwise -1.
Examples:
Input: a = 3, b = 3, c = 3
Output: 9
Explanation: Here is one possible string we can form i.e.
- a = 3 (a, a, a)
- b = 3 (b, b, b)
- c = 3 (c, c, c)
we can create by adding the alternate likewise first a second b, third c.
- abc
- 1+abc -> abc+abc -> abcabc
- 2+abc -> abcabcabc
So, get the last string abcabcabc (as we can see that there is no 3-time repeating character in the string we got) last well output the length of the string i.e. 9.
Approach: This can be solved with the following idea:
The idea is very simple we can use a simple math formula.
Below are the steps involved in the implementation of the code:
- First of all, we create an mx var and find the maximum value from a, b, and c.
- Then we can check if mx ≤ (2*(sum of a, b, and c)-mx+1). if this came True then we can simply output the sum of a+b+c.
- Otherwise, we will output -1.
Below is the implementation of the code:
C++
#include <iostream>
using namespace std;
void getValue( int a, int b, int c)
{
int mx = max(a, max(b, c));
if (mx <= (2*(a + b + c) - mx + 1))
{
cout << a + b + c << endl;
} else {
cout << -1 << endl;
}
}
int main() {
int a = 3;
int b = 3;
int c = 3;
getValue(a, b, c);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static void getValue( int a, int b, int c) {
int mx = Math.max(a, Math.max(b, c));
if (mx <= ( 2 *(a + b + c) - mx + 1 )) {
System.out.println(a + b + c);
} else {
System.out.println(- 1 );
}
}
public static void main(String[] args) {
int a = 3 ;
int b = 3 ;
int c = 3 ;
getValue(a, b, c);
}
}
|
Python
def getValue(a, b, c):
mx = max (a, b, c)
if (mx < = ( 2 * (a + b + c) - mx + 1 )):
print (a + b + c)
else :
print ( - 1 )
a = 3
b = 3
c = 3
getValue(a, b, c)
|
C#
using System;
class GFG {
static void getValue( int a, int b, int c) {
int mx = Math.Max(a, Math.Max(b, c));
if (mx <= (2 * (a + b + c) - mx + 1)) {
Console.WriteLine(a + b + c);
} else {
Console.WriteLine(-1);
}
}
static void Main( string [] args) {
int a = 3;
int b = 3;
int c = 3;
getValue(a, b, c);
}
}
|
Javascript
function getValue(a, b, c) {
let mx = Math.max(a, Math.max(b, c));
if (mx <= (2 * (a + b + c) - mx + 1)) {
console.log(a + b + c);
} else {
console.log(-1);
}
}
let a = 3;
let b = 3;
let c = 3;
getValue(a, b, c);
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
19 Jul, 2023
Like Article
Save Article