Gladingi_BOi's blog

By Gladingi_BOi, 2 years ago, In English

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

  • Vote: I like it
  • -13
  • Vote: I do not like it

| Write comment?
»
2 years ago, # |
Rev. 2   Vote: I like it +5 Vote: I do not like it

max_element is absolutely same cycle. So both codes should use same time.
If AC and TLE solutions differ only there, then I can see two possible reason:

1) AC solution use time close to time limit.
2) Codes returns different results if arr is empty (first returns 0, second returns 1). Maybe outside it is important.