Given a string
You can use each character in the text at most once. Return the maximum number of instances that can be formed.
text
, you want to use the characters of text
to form as many instances of the word "balloon" as possible.You can use each character in the text at most once. Return the maximum number of instances that can be formed.
Example 1:
Input: text = "nlaebolko"
Output: 1
Approach
Java
import java.util.Arrays;import java.util.HashMap;public class MaxNumberBalloons {public static void main(String[] args) {String text = "nlaebolko";System.out.println(maxNumberOfBalloons(text));}static int maxNumberOfBalloons(String text) {int n = text.length();HashMap<Character, Integer> mp = new HashMap<Character, Integer>();for (int i = 0; i < n; i++)mp.put(text.charAt(i), mp.getOrDefault(text.charAt(i), 0) + 1);int arr[] = new int[5];arr[0] = mp.getOrDefault('b', 0);arr[1] = mp.getOrDefault('a', 0);arr[2] = mp.getOrDefault('l', 0) / 2;arr[3] = mp.getOrDefault('o', 0) / 2;arr[4] = mp.getOrDefault('n', 0);Arrays.sort(arr);return arr[0];}}
C++
#include <bits/stdc++.h>using namespace std;int maxNumberOfBalloons(string text){int n = text.size();map<char, int> mp;for (int i = 0; i < n; i++)mp[text[i]]++;int arr[5];arr[0] = mp['b'];arr[1] = mp['a'];arr[2] = mp['l'] / 2;arr[3] = mp['o'] / 2;arr[4] = mp['n'];sort(arr, arr + 5);return arr[0];}int main(){string text = "nlaebolko";cout << maxNumberOfBalloons(text);return 0;}
No comments:
Post a Comment