Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://practice.geeksforgeeks.org/contest/gfg-weekly-coding-contest-86/problems/#
- Given a string s of length n, maximize the number of possible *anagrams by doing atmost k special operations.
- A special operation is defined as replacing any character with any of the available 26 lower case alphabets. After doing atmost k operations return the total number of anagrams.
- Since the answer can be very large, return the answer modulo 10^9+7.
- *anagrams :- An anagram is a word or phrase formed by rearranging the letters of another word or phrase. For example, the word "listen" can be rearranged into "silent".
- Input : N=3 K=1 s="aac"
- Output : 6
- Explaination :
- After applying one operation we can "a" on first index to "b" and
- 6 possible anagrams are "abc","acb","bca","bac","cab","cba"
- Input : N=3 K=2 s="abc"
- Output: 6
- Explaination :
- The string "abc" itself has the maximum possible anagrams.
- Your Task:
- Your task is to count the number of possible anagrams modulo 10^9 + 7 .
- Constraints:
- 1 <= N <= 10 ^ 5
- 1 <= K <= 10 ^ 5
- --------------------------------------------------------------------------------------------------------------------------------------
- int mod=1000000007;
- long long int binaryExpo(long long int x, long long int power){
- long long int res=1;
- while(power>0){
- if(power%2==0){
- x=(x*x)%mod;
- power/=2;
- }
- else{
- res=(res*x)%mod;
- power=power-1;
- }
- }
- return res;
- }
- int fact(long long int n){
- long long int res=1;
- for(int i=1;i<=n;i++){
- res=(res*i)%mod;
- }
- return res%mod;
- }
- int maximumPossible(int n,int k,string s){
- int freq[26]={0};
- for(auto c: s){
- freq[c-'a']++;
- }
- multiset<pair<int,char>> mpp; // you can get away using only freq, but using a char helps to visual.
- for(int i=0;i<26;i++){
- mpp.insert({freq[i],i+'a'});
- }
- k=min(k,n); // the maximum change you can do is just n only at max
- while(k>0 && abs(mpp.begin()->first-mpp.rbegin()->first)>=2){
- auto tp=*mpp.begin();
- mpp.erase(mpp.begin());
- auto rp=*mpp.rbegin();
- mpp.erase(--mpp.end());
- tp.first++;
- mpp.insert(tp);
- rp.first--;
- mpp.insert(rp);
- k--;
- }
- int res=fact(n);
- for(auto m: mpp){
- int fx=fact(m.first);
- res=(res*binaryExpo(fx,mod-2))%mod; // fermat little theorem
- }
- return res;
- }
Advertisement
Add Comment
Please, Sign In to add comment