fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. int[][] array = {{1, 2, 3},
  13. {2, 3, 1},
  14. {3, 1, 2}};
  15. Stack<Integer> stack = new Stack<Integer>(); // stores the index only
  16. int[][] output = new int[array.length][array[0].length];
  17. for (int i = array.length-1; i >= 0; i--) // direction not important
  18. {
  19. stack.clear();
  20. for (int j = array[0].length-1; j >= 0; j--)
  21. {
  22. while (!stack.empty() && array[i][stack.peek()] < array[i][j])
  23. stack.pop();
  24. int offset;
  25. if (stack.empty())
  26. offset = array[0].length;
  27. else
  28. offset = stack.peek();
  29. output[i][j] = offset - j - 1;
  30. stack.push(j);
  31. }
  32. }
  33.  
  34. for (int i = array[0].length-1; i >= 0; i--) // direction not important
  35. {
  36. stack.clear();
  37. for (int j = array.length-1; j >= 0; j--)
  38. {
  39. while (!stack.empty() && array[stack.peek()][i] < array[j][i])
  40. stack.pop();
  41. int offset;
  42. if (stack.empty())
  43. offset = array.length;
  44. else
  45. offset = stack.peek();
  46. output[j][i] += offset - j - 1;
  47. stack.push(j);
  48. }
  49. }
  50.  
  51. for (int i = 0; i < array.length; i++)
  52. for (int j = 0; j < array[0].length; j++)
  53. output[i][j] += 1;
  54.  
  55. for (int[] a: output)
  56. System.out.println(Arrays.toString(a));
  57. }
  58. }
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
[1, 1, 3]
[1, 3, 1]
[3, 1, 1]