Help me in solving NEXTPERM problem

My issue

if given permutation is itself lexicographical largest what should be output

My code

#include <iostream>
using namespace std;

int main() {
	// your code goes here
	int n,k;
	cin>>n>>k;
	while(k--){
	    vector<int>v;
	    for(int i=0;i<n;i++){
	        int x;cin>>x;
	        v.push_back(x);
	    }
	    
	    map<int,int>mp;
	    mp[n-1]=n-1;
	    for(int i=n-2;flag==0&&i>=0;i++){
	        auto it=mp.upper_bound(v[i]);
	        if(it==mp.end())
	        mp[v[i]]=i;
	        else{
	            swap(v[it.second],v[i]);
	            sort(v.begin()+i,v.end());
	            flag=1;
	        }
	    }
	    if
	    
	}
	return 0;
}

Problem Link: CodeChef: Practical coding for everyone