#include<bits/stdc++.h>
using namespace std;
#define mod (1000000007)
int main(){
int t;
cin>>t;
while (t!=0)
{
int n;
cin>>n;
int a[n];
for (int i = 0; i < n; i++)
{cin>>a[i];}
sort(a,a+n);
int year=0,sum=0;
for (int i = n-1; i >=0; i--)
{ if (a[i]-year>0)
{
sum=sum+(a[i]-year)%mod;
year++;
}
}
cout<<sum%1000000007<<endl;
t--;
}
return 0;
}
Can you link the question too ? It’s very difficult to optimise a code without seeing the question 
2 Likes
you are not decrementing the variable t …It should be t-- instead of t != 0
tried that but still not working
Can you please format your code properly? I dunno why most people don’t do it.
1 Like
use this lk to access code
Is it still TLE, or WA. Because I think it might over flow! Try doing sum%=MOD everytime you add something to it.
Or better, as suggested, just use long long! Code
Try this:
#include<bits/stdc++.h>
using namespace std;
#define mod (1000000007)
int main(){
int t;
cin>>t;
while (t–)
{
int n;
cin>>n;
long long a[n];
for (int i = 0; i < n; i++)
{
cin>>a[i];
}
sort(a,a+n);
int year=0;
long long sum = 0;
for (int i = n-1; i >=0; i--)
{ if (a[i]-year>0)
{
sum=(sum+a[i]-year)%mod;
year++;
}
else
{
break;
}
}
cout<<sum%mod<<endl;
}
return 0;
}
Use long long instead of int… this will work
Well you can use the following way also:
static int compute_maximum_profit(std :: vector <int> & car_price, const int n) {
std :: sort(car_price.rbegin(), car_price.rend()); // Sorts the data in decreasing order.
int max_profit = 0;
for(int i = 0; i < n; ++i) {
if(car_price[i] - i > 0) {
car_price[i] -= i;
max_profit = (max_profit + car_price[i]) % MOD;
}
}
return max_profit;
}
Complete Code Link: Competitive-Programming/Code-Chef/Sell-All-The-Cars at master · strikersps/Competitive-Programming · GitHub
Using long long might help!
Below is my code :
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define mod 1000000007
void shammi() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
int main() {
shammi();
ll t; cin >> t;
while (t--) {
ll n, sum = 0; cin >> n;
ll P[n];
for (ll i = 0; i < n; i++) cin >> P[i];
sort(P, P + n);
for (ll i = n - 1; i >= 0; i--) {
if ((P[i] - (n - i - 1)) >= 0) {
sum += (P[i] - (n - i - 1));
sum = sum % mod;
}
}
cout << sum % mod << "\n";
}
return 0;
}
use vector and perform sort(a.rbegin(), a.rend()); don’t maintain extra variable year the sum should be max(0, a[i]-i); and write sum%= mod. last mod is not required. Array seems less optimized