#C7758. Minimum Operations to Stabilize Stack Heights

    ID: 51664 Type: Default 1000ms 256MiB

Minimum Operations to Stabilize Stack Heights

Minimum Operations to Stabilize Stack Heights

You are given several stacks with certain heights. In one operation, you can reduce the height of a stack so that it does not exceed the height of the stack immediately to its right. The goal is to achieve a configuration such that for every stack, its height is no more than the height of the stack to its right.

Given the initial heights for each test case, compute the minimum number of operations required to achieve this condition. Formally, for an array of heights a1, a2, ..., an, you want to ensure that

[ a_i \leq a_{i+1} \quad \text{for all} \quad 1 \leq i < n, ]

where reducing a stack’s height by 1 counts as one operation. Note that you are only allowed to decrease the heights.

Example:

  • Input: [5, 7, 4, 8]
  • Operation: Decrease 7 to 4 (3 operations) and decrease 5 to 4 (1 operation).
  • Total operations = 4.

inputFormat

The input is given via standard input with the following format:

T
n1
h1 h2 ... hn1
n2
h1 h2 ... hn2
...

Where:

  • T is the number of test cases.
  • For each test case, the first line contains an integer n, the number of stacks.
  • The next line contains n space-separated integers representing the heights of the stacks.

outputFormat

For each test case, output a single line containing the minimum number of operations required.

The output should be printed to standard output.

## sample
2
4
5 7 4 8
3
3 2 1
4

3

</p>