AcWing 1574. 接雨水
原题链接
简单
import java.util.*;
public class Main{
static final int N = 100010;
static int[] g = new int[N];
static int[] st = new int[N];
static int n , top = 0 , res = 0 , last = 0;
public static void main(String[] args){
Scanner s = new Scanner(System.in);
n = s.nextInt();
for(int i = 0 ; i < n ; i ++) g[i] = s.nextInt();
for(int i = 0 ; i < n ; i ++){
while(top > 0 && g[st[top]] < g[i]){
res += (g[st[top]] - last) * (i - st[top] - 1);
last = g[st[top]];
top --;
}
if(top > 0) res += (g[i] - last) * (i - st[top] - 1);
st[++ top] = i;
}
System.out.println(res);
}
}