数组倒序遍历,单调递增栈
[code=java]
public class 分奖金 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int[] ans = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = a.length - 1; i >= 0; i--) {
while (!stack.isEmpty() && a[i] >= a[stack.peek()]) { // 单调栈,栈顶小,栈底大
stack.pop();
}
if (stack.isEmpty()) {
ans[i] = a[i];
} else {
ans[i] = (stack.peek() - i) * (a[stack.peek()] - a[i]);
}
stack.push(i); // 栈里是以a[i]开头的递增子序列,前一个数a[i-1]就是在此基础上找第一个大于它的数
}
StringJoiner sj = new StringJoiner(" ");
for (int x : ans) sj.add("" + x);
System.out.println(sj);
}
}
[/code]