fork download
  1. /*Write a program to take an array arr[] of integers as input, the task is to find the previous greater element
  2. for each element of the array in order of their appearance in the array. Previous greater element of an element
  3. in the array is the nearest element on the left which is greater than the current element. If there does not exist
  4. next greater of current element, then previous 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.  
  10. #include <stdio.h>
  11.  
  12. int main() {
  13. int n;
  14. scanf("%d", &n);
  15.  
  16. int arr[n];
  17. for (int i = 0; i < n; i++) scanf("%d", &arr[i]);
  18.  
  19. for (int i = 0; i < n; i++) {
  20. int pge = -1;
  21.  
  22. for (int j = i - 1; j >= 0; j--) { // look to the left
  23. if (arr[j] > arr[i]) {
  24. pge = arr[j];
  25. break;
  26. }
  27. }
  28.  
  29. printf("%d", pge);
  30. if (i != n - 1) printf(",");
  31. }
  32.  
  33. return 0;
  34. }
  35.  
Success #stdin #stdout 0s 5324KB
stdin
6
4 5 2 25 7 8
stdout
-1,-1,5,-1,25,25