Leetcode 1189. Maximum Number of Balloons
Given a string text
, you want to use the characters of text
to form as many instances of the word “balloon” as possible. You can only use each character in text
once. Return the maximum number of instances that can be formed.
text
?
text
contain characters other than lowercase English letters?
#include <iostream>
#include <unordered_map>
#include <string>
#include <algorithm>
int maxNumberOfBalloons(const std::string& text) {
std::unordered_map<char, int> char_count;
// Count frequency of each character in the text
for (char ch : text) {
char_count[ch]++;
}
// Calculate the maximum number of "balloon"
int b_count = char_count['b'];
int a_count = char_count['a'];
int l_count = char_count['l'] / 2;
int o_count = char_count['o'] / 2;
int n_count = char_count['n'];
// Minimum of these counts will be the answer
return std::min({b_count, a_count, l_count, o_count, n_count});
}
int main() {
std::string text = "nlaebolko";
std::cout << "Maximum number of 'balloon' instances: " << maxNumberOfBalloons(text) << std::endl;
return 0;
}
n
is the length of the string. This is because we only need to traverse the string once to count the frequencies of the characters.unordered_map
).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?