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 Main
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. Scanner sc = new Scanner(System.in);
  14. int n = sc.nextInt();
  15. int[] arr = new int[n];
  16. Map<Integer, Integer> first = new HashMap<>();
  17. Map<Integer, Integer> last = new HashMap<>();
  18. for(int i=0;i<n;i++){
  19. arr[i] = sc.nextInt();
  20. if(!first.containsKey(arr[i])){
  21. first.put(arr[i],i);
  22. }
  23. last.put(arr[i],i);
  24. }
  25. Integer[] sorted = first.keySet().toArray(new Integer[0]);
  26. Arrays.sort(sorted, Collections.reverseOrder());
  27.  
  28. int sum = 0;
  29. int preIdx = first.get(sorted[0]);
  30. int sufIdx = last.get(sorted[0]);
  31. if(preIdx<sufIdx){
  32. sum += sorted[0]*(sufIdx-preIdx-1) + 2*sorted[0];
  33. }
  34. else{
  35. sum += sorted[0];
  36. }
  37.  
  38. for(int i=1;i<sorted.length;i++){
  39. int leftIdx = first.get(sorted[i]);
  40. int rightIdx = last.get(sorted[i]);
  41.  
  42. if(leftIdx<preIdx){
  43. sum += sorted[i]*(preIdx - leftIdx - 1) + sorted[i];
  44. preIdx = leftIdx;
  45. }
  46. if(rightIdx > sufIdx){
  47. sum += sorted[i]*(rightIdx-sufIdx - 1) + sorted[i];
  48. sufIdx = rightIdx;
  49. }
  50. }
  51. System.out.println(sum);
  52. }
  53. }
Success #stdin #stdout 0.13s 56548KB
stdin
14
1 4 2 5 1 1 5 1 5 1 4 1 3 1
stdout
54