Code 1
int canWin(int n, vector < int > arr) {
int count=0;
int maxElement = 0;
for(int i=0;i<n;i++){
maxElement=max(maxElement,arr[i]);
}
for(int i=0;i<n;i++){
if(maxElement==arr[i]) count++;
}
return count==1 ? 1 : 0;
}
Code 2
int canWin(int n, vector < int > arr) {
int res=*max_element(arr.begin(),arr.end());
int cnt=0;
for(int i=0;i<arr.size();i++)
if(arr[i]==res)
cnt++;
return cnt>1 ? 0 : 1;
}
Code 1 passes all the test cases but code 2 gives TLE. Why is this happening? Problem Link: Ninja and His Hero