54 容器盛水问题
Table of Contents

ac

import java.util.*;


public class Main {

    public static Scanner sc = new Scanner(System.in);

    static int mod = 1_000_000_000 + 7;

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        int n = sc.nextInt();
        int[] arr = new int[n];
        for(int i=0;i<n;i++){
            arr[i] = sc.nextInt();
        }
        if(n < 3){
            System.out.println(0);
            return;
        }
        Stack<Integer> sta = new Stack<>();
        sta.push(arr[0]);
        long ans = 0;
        int maxVal = arr[0];
        for(int i=1;i<n;i++){
            if(sta.isEmpty()){
                sta.push(arr[i]);
                maxVal = arr[i];
            }else {
                if(arr[i] >= maxVal){
                    // 最大了
                    while (!sta.isEmpty()){
                        int val = sta.peek();
                        sta.pop();
                        ans += (maxVal - val);
                    }
                    maxVal = arr[i];
                    sta.push(arr[i]);
                }else {
                    // 比栈最大值小,就入栈
                    sta.push(arr[i]);
                }
            }
        }
        if(!sta.isEmpty()){
            // 反过来处理
            Stack<Integer> sta2 = new Stack<>();
            sta2.push(sta.peek());
            sta.pop();
            maxVal = sta2.peek();
            while (!sta.isEmpty()){
                int arri = sta.pop();
                if(sta2.isEmpty()){
                    sta2.push(arri);
                    maxVal = arri;
                }else {
                    if(arri >= maxVal){
                        // 最大了
                        while (!sta2.isEmpty()){
                            int val = sta2.pop();
                            ans += (maxVal - val);
                        }
                        maxVal = arri;
                        sta2.push(arri);
                    }else {
                        // 比栈最大值小,就入栈
                        sta2.push(arri);
                    }
                }
            }
        }
        System.out.println(ans);
    }

}

/*
6
3 1 2 5 2 4

5
 */