Domain: Algorithms & Data Structures

## Problem: Eliminate “+1 Later” Conflicts

You are given an integer sequence `a` of length `n`. Call a sequence `b` **valid** if there are **no** positions `i < j` such that:

\[
b_j = b_i + 1
\]

In other words, you must avoid any situation where a value appears and **somewhere later** a value exactly **one larger** appears.

You may delete elements from `a` (keeping the remaining elements in their original order). Your task is to compute the **minimum number of deletions** required so that the remaining sequence becomes valid.

---

## Input
The input contains multiple test cases.

- The first line contains an integer `t` (`1 ≤ t ≤ 6·10^4`) — the number of test cases.
- For each test case:
  - The first line contains an integer `n` (`1 ≤ n ≤ 3·10^5`) — the length of the sequence.
  - The second line contains `n` integers `a1, a2, …, an` (`1 ≤ ai ≤ n`).

It is guaranteed that the sum of `n` over all test cases does not exceed `3·10^5`.

---

## Output
For each test case, output one integer: the minimum number of elements that must be removed from `a` so that the remaining sequence is valid.


Grading rubric:
criterion: Does the answer state the forbidden pattern as existence of indices i<j with b[j] = b[i] + 1?
weight: 1
criterion: Does the answer sort the pair list by value in non-decreasing order?
weight: 1
criterion: Does the answer define dp[i] as the maximum size of a good selection whose last chosen pair is the i-th pair in the sorted list?
weight: 1
criterion: Does the answer include a maintained maximum over dp[j] for processed pairs satisfying value[j] ≤ value[i] − 2?
weight: 1
criterion: Does the answer include a query for the maximum dp among processed pairs satisfying (value = current value − 1, position > current position)?
weight: 1
criterion: Does the answer state that the final result equals n minus the maximum attainable kept length (answer = n − keep)?
weight: 1
criterion: Does the answer construct a list of pairs (a[i], i) using the original index as the second component?
weight: 1
criterion: Does the answer specify that equal values are tie-broken by sorting indices in non-increasing (descending) order?
weight: 1
criterion: Does the answer specify the disallowed transition condition (value[i] = value[j] + 1, pos[i] > pos[j])?
weight: 1
criterion: Does the answer include a maintained maximum dp among processed pairs with value equal to the current value?
weight: 1

Answer:
### Key reformulation
We want to keep as many elements as possible. Let `keep` be the maximum size of a subsequence that is **good**; then the answer is:

\[
\text{removed} = n - keep
\]

A subsequence is **not good** exactly when it contains two chosen indices `p<q` with `a[q]=a[p]+1`.
So, if we choose some elements of value `x` and some of value `x+1`, then **every chosen `(x+1)` must lie strictly to the left of every chosen `x`**.

---

### Step 1: Sort values with positions
Create pairs `(value, position)` for all indices.

Sort these pairs by:
1. `value` increasing
2. `position` decreasing for equal values

Call the sorted list `v[1..n]`, where `v[i] = (val[i], pos[i])`.

This tie-break (positions descending inside equal values) will let us treat “taking multiple equal values” cleanly while enforcing constraints only between consecutive values.

---

### Step 2: DP definition
Define:

- `dp[i]` = maximum number of kept elements in a good subsequence **whose last selected pair is exactly** `v[i]`.

Then:

\[
dp[i] = 1 + \max dp[j]
\]
over all `j < i` that can precede `i` without creating a forbidden `(+1 later)` pair.

When is transition `j -> i` invalid?
- It is invalid only in the specific case:
  - `val[i] = val[j] + 1` **and**
  - `pos[i] > pos[j]`
  
Because that would mean an element of value `val[j]` occurs earlier in the kept subsequence and a `+1` occurs later, which is forbidden.

So the transition is allowed iff:

\[
val[i] \ne val[j] + 1 \quad \text{or} \quad pos[i] < pos[j]
\]

Finally:

\[
keep = \max_{1 \le i \le n} dp[i], 
\quad \text{answer} = n - keep
\]

---

### Step 3: Speeding up the transition
A direct computation is `O(n^2)`, too slow. We optimize by splitting candidates `j` into three disjoint groups:

#### A) Values at most `val[i]-2`
If `val[j] <= val[i]-2`, then `val[i]` cannot equal `val[j]+1`, so the transition is always valid.

Maintain:
- `bestSmall` = maximum `dp[j]` among all processed `j` with `val[j] <= currentValue-2`.

#### B) Same value: `val[j] = val[i]`
Always valid (since the forbidden condition requires `+1` difference).

Maintain:
- `bestSame[value]` = maximum `dp[j]` seen so far for this exact value.

#### C) Previous value: `val[j] = val[i]-1`
This is the only case where position matters. We need `pos[i] < pos[j]`.

Inside each value group, positions are processed in **decreasing** order (because of the sort).
So for value `val[i]-1`, we can maintain a structure that answers:
- maximum `dp[j]` among those earlier in the group with `pos[j] > pos[i]`

This can be done with a running **suffix maximum over the group** (equivalently: as you sweep positions downward, maintain the best dp seen so far).

Call this query result:
- `bestPrevGreaterPos`

Then:

\[
dp[i] = 1 + \max\big(bestSmall,\; bestSame[val[i]],\; bestPrevGreaterPos\big)
\]

After computing `dp[i]`, update the maintained maxima for future steps.

---

### Complexity
- Sorting pairs: `O(n log n)` per test file (overall across test cases).
- DP with maintained maxima: `O(n)` after sorting.
- Total across all tests: `O((\sum n)\log(\sum n))`, with `\sum n \le 3\cdot 10^5`.

This meets the constraints.

---