fork download
  1.  
  2. /*
  3. this is quick fix for your solution since we don't need an array to store the value
  4. and then perform a scan after to find the minimum it's unecessery loops and waste of time
  5. to store the values in an arrays.
  6. but this solution still gives TLE
  7. */
  8.  
  9. #include<bits/stdc++.h>
  10. using namespace std;
  11.  
  12.  
  13. const int INF = 1e5 + 5;
  14.  
  15. void solve(){
  16. int a,b;
  17. cin >> a >> b;
  18. vector<int> arr(a);
  19. for(int& x : arr) {
  20. scanf("%d", &x);
  21. }
  22. int ans = INF;
  23. for(int i=0; i < a; i++){
  24. for(int j = i+1; j <= i + b && j < a; j++){
  25. if(arr[i]==arr[j]) {
  26. ans = min(ans, arr[i]);
  27. }
  28. }
  29. }
  30. printf("%d\n", ans != INF ? ans : -1);
  31. }
  32.  
  33.  
  34. int main(){
  35. solve();
  36. return 0;
  37. }
  38.  
  39.  
  40.  
  41. /*
  42. Another improvement we can do is to remove some loops if we have computed the answer
  43. */
  44. #include<bits/stdc++.h>
  45. using namespace std;
  46.  
  47. const int INF = 1e5 + 5;
  48.  
  49. void solve(){
  50. int a,b;
  51. cin >> a >> b;
  52. vector<int> arr(a);
  53. for(int& x : arr) {
  54. scanf("%d", &x);
  55. }
  56. set<int> S;
  57. int ans = INF;
  58. for(int i=0; i < a; i++){
  59. if(!S.count(arr[i])) {
  60. for(int j = i+1; j <= i + b && j < a; j++){
  61. if(arr[i]==arr[j]) {
  62. ans = min(ans, arr[i]);
  63. S.insert(arr[i]);
  64. break;
  65. }
  66. }
  67. }
  68. }
  69. printf("%d\n", ans != INF ? ans : -1);
  70. }
  71.  
  72. int main(){
  73. solve();
  74. return 0;
  75. }
  76.  
  77. // still this gives error so try to come up with a solution that works in O(n) or O(nlog(n))
  78.  
  79.  
  80.  
Compilation error #stdin compilation error #stdout 0s 5300KB
stdin
Standard input is empty
compilation info
prog.cpp:47:11: error: redefinition of ‘const int INF’
 const int INF = 1e5 + 5;
           ^~~
prog.cpp:13:11: note: ‘const int INF’ previously defined here
 const int INF = 1e5 + 5;
           ^~~
prog.cpp:49:6: error: redefinition of ‘void solve()’
 void solve(){
      ^~~~~
prog.cpp:15:6: note: ‘void solve()’ previously defined here
 void solve(){
      ^~~~~
prog.cpp:72:5: error: redefinition of ‘int main()’
 int main(){
     ^~~~
prog.cpp:34:5: note: ‘int main()’ previously defined here
 int main(){
     ^~~~
prog.cpp: In function ‘void solve()’:
prog.cpp:20:8: warning: ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]
   scanf("%d", &x);
   ~~~~~^~~~~~~~~~
prog.cpp: In function ‘void solve()’:
prog.cpp:54:8: warning: ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]
   scanf("%d", &x);
   ~~~~~^~~~~~~~~~
stdout
Standard output is empty