fork download
  1. /*Write a program to take an array arr[] of integers as input, the task is to find the next greater element for
  2. each element of the array in order of their appearance in the array. Next greater element of an element in the
  3. array is the nearest element on the right which is greater than the current element. If there does not exist next
  4. greater of current element, then next greater element for current element is -1.
  5.  
  6. N.B:
  7. - Print the output for each element in a comma separated fashion.
  8. - Do not use Stack, use brute force approach (nested loop) to solve.*/
  9. #include <stdio.h>
  10.  
  11. int main() {
  12. int n;
  13. scanf("%d", &n);
  14.  
  15. int arr[n];
  16. for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
  17.  
  18. for (int i = 0; i < n; i++) {
  19. int nge = -1;
  20. for (int j = i + 1; j < n; j++) {
  21. if (arr[j] > arr[i]) {
  22. nge = arr[j];
  23. break;
  24. }
  25. }
  26.  
  27. printf("%d", nge);
  28. if (i != n - 1) printf(","); // comma separated
  29. }
  30.  
  31. return 0;
  32. }
  33.  
Success #stdin #stdout 0.01s 5324KB
stdin
6
4 5 2 25 7 8
stdout
5,25,25,-1,8,-1