Find Duplicate Element in K-Distance

Problem Statement:

Program to find duplicate element in k-distance. If found print "YES" otherwise "NO".

Source Code:
#include<stdio.h>
int main(){
    int n,ary[50],k,flag=0;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&ary[i]);
    }
    scanf("%d",&k);
    for(int i=0;i<n-k;i++){
        for(int j=i+1;j<=(i+k);j++){
            printf("%d\n",j);
            if(ary[i]==ary[j]){
                flag=1;
                break;
            }
        }
    }
    if(flag==1){
        printf("YES");
    }else{
        printf("NO");
    }
  return 0;
}
SAMPLE INPUT1:
8
1 2 3 4 1 2 3 4
3
SAMPLE OUTPUT1:
NO

SAMPLE INPUT2:
6
1 2 3 2 4 5
3
SAMPLE OUTPUT2:
YES