- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Number of Frogs Croaking in C++
Suppose we have a string called croakOfFrogs, this represents a combination of the string "croak" from different frogs, multiple frogs can croak at the same time, so multiple "croak" are mixed. We have to find the minimum number of different frogs to finish all the croak in the given string.
Here a valid "croak" means a frog is generating 5 letters ‘c’, ’r’, ’o’, ’a’, ’k’ sequentially. The frogs have to generate all five letters to finish a croak. If the string is not a valid "croak" string then return -1.
So, if the input is like "crcoakroak", then the output will be 2 as the first frog could yell "crcoakroak". The second frog could yell later "crcoakroak".
To solve this, we will follow these steps −
Define one map m
Define an array ch of size: 5 assign it with {'c', 'r', 'o', 'a', 'k'}
temp := 0, ret := 0
for each element c in s, do
(increase m[c] by 1)
maxVal := m[ch[0]]
for initialize i := 0, when i < 5, update (increase i by 1), do −
if maxVal < m[ch[i]] or m[ch[i]] < 0, then −
return -1
maxVal := m[ch[i]]
if c is same as 'c', then −
(increase temp by 1)
otherwise when c is same as 'k', then −
(decrease temp by 1)
ret := maximum of ret and temp
for initialize i := 1, when i < 5, update (increase i by 1), do −
if m[ch[0]] is not equal to m[ch[i]], then −
return -1
return ret
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int minNumberOfFrogs(string s) { map<char, int> m; char ch[5] = { 'c', 'r', 'o', 'a', 'k' }; int temp = 0; int ret = 0; for (auto& c : s) { m[c]++; int maxVal = m[ch[0]]; for (int i = 0; i < 5; i++) { if (maxVal < m[ch[i]] || m[ch[i]] < 0) { return -1; } maxVal = m[ch[i]]; } if (c == 'c') { temp++; } else if (c == 'k') { temp--; } ret = max(ret, temp); } for (int i = 1; i < 5; i++) { if (m[ch[0]] != m[ch[i]]) return -1; } return ret; } }; main(){ Solution ob; cout << (ob.minNumberOfFrogs("crcoakroak")); }
Input
"crcoakroak"
Output
2