Help me in solving ENDCORR problem

My issue

Why do I get a time limit exceeded in half of my test cases. The algorithm I have used is to sort the current total citizens, execute richest and set it to 0 so it does not repeat when sorted in descending order

My code

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int largest(int ctz[],int n, int v){
    sort(ctz, ctz + n+1, greater<int>());
    cout << ctz[0] << endl;
    ctz[0] = 0;
    return 0;
}

int main() {
	// your code goes here
	int n,m;
	cin >> n >> m;
	int ctz[n], behead[m];
	int v = 0;
	for(int i = 0; i < n+m; i++)
	{
	    int a;
	    cin >> a;
	    if (a == -1)
	    {

	        //cout << v << endl;
	        v++;
	        largest(ctz,i-v,v-1);
	        
	    }
	    else
	    {
	        ctz[i-v] = a;
	        //cout << ctz[i-v] << endl;
	    }
	    
	}
	/*
    for(int y = 0; y < n; y++)
    {
        cout << ctz[y] << endl;
    }
    cout <<endl;*/
	return 0;
}

Problem Link: CodeChef: Practical coding for everyone

@tssbrisingr
The constraint of n and m are uptil 10^5 .
and inside for loop which will run till n U are calling a function which will perform sorting and do other stuffs .
The time complexity of sorting is nlogn.
so the total time complexity will become O(n^2logn).
So u have to optimize your solution .