Help me in solving SWAPUNITE problem

My issue

im trying to find each occurrences of character . I m taking maximum occurrence if it has unity then im taking 0 and if not then the remaining scattered its values im adding it up as n - high_occurred value. why my approach is wrong

My code

#include <bits/stdc++.h>
using namespace std;

int main() {
	// your code goes here
    int t;cin>>t;
    while(t--){
        map<char,int>m;
        string s; cin>>s;
        vector<int>v;
        int c = 1,maxc = 1;
        for(int i=0;i<s.size();i++){
            if (s[i]==s[i+1]){
                c++;
            }else{
                m[s[i]] = max(m[s[i]],c);
                c =1;
            }
        }for(auto [a,b]:m){
            if (count(s.begin(),s.end(),a)==b) {
                v.push_back(0);
            }else{
                v.push_back(count(s.begin(),s.end(),a) - b);
            }
        }
        cout<<*min_element(v.begin(),v.end())<<endl;
        
    }
}

Problem Link: Swap and Unite Practice Coding Problem - CodeChef

@goku87
U have to apply sliding window on each character to get the optimal answer
plzz refer my c++ code for better understanding

#include <bits/stdc++.h>
using namespace std;

int main() {
	// your code goes here
    int t;
    cin>>t;
    while(t--)
    {
        string s;
        cin>>s;
        map<char,int> mp;
        for(int i=0;i<s.size();i++)
        {
            mp[s[i]]++;
        }
        int ans=INT_MAX;
        for(auto x:mp)
        {
         map<char,int> mp1;   
            for(int i=0;i<x.second;i++)
            {
                mp1[s[i]]++;
            }
           ans=min(ans,x.second-mp1[x.first]);
           for(int i=x.second;i<s.size();i++)
           {
               mp1[s[i]]++;
               mp1[s[i-x.second]]--;
               ans=min(ans,x.second-mp1[x.first]);
           }
        }
        cout<<ans<<endl;
    }

}
1 Like