My code is giving wrong answer. Can anyone explain why?

Here is the question link
This the code which gives me correct output but in submission it shows me wrong answer. Please help me out & explain why it’s happening?

#include <bits/stdc++.h>
using namespace std;
int main() {
	int t;
	cin>>t;
	while(t--){
	    int n,i;
        cin>>n;
	    int arr[n];
	    bool flag = false;
	    for (int i = 0; i < n; i++) {
	        cin>>arr[i];
	    }
	    sort(arr, arr+n);
	    for (i = 0; i < n; i=i+2){
	        if(arr[i]==arr[i+1]){
                flag = true;
	        }
	        else{
	            flag = false;
	        }
	    }
	    if(flag == false){
	    cout<<arr[n-1];
	    }
	}
	return 0;
}

Index-out-of-bounds access for sample test input:

[simon@simon-laptop][11:40:06]
[~/devel/hackerrank/otherpeoples]>./compile-latest-cpp.sh 
Compiling arnab2002-MISSP.cpp
Executing command:
  g++ -std=c++17 arnab2002-MISSP.cpp -O3 -g3 -Wall -Wextra -Wconversion -DONLINE_JUDGE -D_GLIBCXX_DEBUG    -fsanitize=undefined -ftrapv
Successful
[simon@simon-laptop][11:40:14]
[~/devel/hackerrank/otherpeoples]>echo "1
5
1
1
2
2
3" | ./a.out
arnab2002-MISSP.cpp:16:28: runtime error: index 5 out of bounds for type 'int [*]'
3

Edit:

Once you’ve fixed that, consider the test input:

2
3
1 
2
1
3
1 
2
1

Edit:

Then after you’ve fixed that, consider the test input:

1                
5
1
1
2
3
3
1 Like