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. Scanner sc = new Scanner(System.in);
  13. int n = sc.nextInt();
  14. int[] heights = new int[n];
  15.  
  16. for (int i = 0; i < n; i++) {
  17. heights[i] = sc.nextInt();
  18. }
  19.  
  20. Stack<Integer> stack = new Stack<>();
  21. int[] nextGreater = new int[n];
  22.  
  23. for (int i = n - 1; i >= 0; i--) {
  24. while (!stack.isEmpty() && stack.peek() <= heights[i]) {
  25. stack.pop();
  26. }
  27.  
  28. if (!stack.isEmpty()) {
  29. nextGreater[i] = stack.peek();
  30. } else {
  31. nextGreater[i] = 0;
  32. }
  33.  
  34. stack.push(heights[i]);
  35. }
  36.  
  37. long sum = 0;
  38. for (int h : nextGreater) {
  39. sum += h;
  40. }
  41.  
  42. System.out.println(sum);
  43. }
  44. }
Success #stdin #stdout 0.12s 54644KB
stdin
5
6
12
16
15
5
stdout
28