↵
This post describes an alternative
↵
The idea
↵
↵
↵
↵
Let
↵
$$$↵
P_0=0,\qqua
The sum of the subarray from
↵
$$$↵
We require
↵
$$$↵
$$$↵
↵
↵
$
↵
Thus
Therefore, for every right endpoint $
↵
$$$↵
$$$
↵
Choosing the largest valid $
↵
---
↵
## Removing
↵
Suppose
↵
$$$↵
x<y↵
$$$↵
↵
and↵
↵
$$$↵
$$$
↵
Then prefix index $
↵
↵
$$$↵
P_i-P_x\geq K,↵
$$$↵
↵
then, because $$$P_y\leq P_x$$$,
↵
$
$$$
↵
because $P_y\leq P_x$.↵
↵
Moreover,
↵
$$$↵
i-y<i-x.↵
$$$↵
↵
Therefore, whenever $$$x$$$ is valid, $$$y$$$ is also valid and
↵
Hence, whenever a new prefix sum arrives, every previous prefix sum greater than or equal to it can be removed permanently.↵
↵
```cpp↵
while (!a.empty() && a.back().first >= p[i]) {↵
a.pop_back();↵
}↵
a.push_back({p[i], i});↵
```↵
↵
After every insertion, the stored pairs satisfy↵
↵
$
$$
↵
and↵
↵
$
Thus, the vector is increasing in both prefix sum and index.↵
↵
↵
↵
For the current endpoint $
↵
$$$↵
We need the last stored pair whose prefix sum is at most $
↵
Since the prefix sums are increasing, all valid pairs form a prefix of the vector.
↵
↵
Therefore, we use:↵
↵
```cpp↵
int pos = upper_bound(↵
a.begin(),↵
a.end(),↵
make_pair(p[i] - k, i)↵
) - a.begin() - 1;↵
```↵
↵
Searching for
↵
$$$↵
\left(P_i-K,\ i\right)↵
$$$↵
↵
↵
$$$↵
↵
---↵
## Correctness
↵
### Lemma 1↵
↵
If
↵
↵
Whenever $
↵
$$$↵
P_i-P_x\geq K.↵
$$$↵
↵
Sinc
↵
$$$↵
P_i-P_y\geq P_i-P_x\geq K.↵
$$$↵
↵
Thus, $$$y$$$ is also valid.
↵
Since
↵
$$$↵
i-y<i-x.↵
$$$↵
↵
↵
### Lemma 2↵
↵
The maintained vector is strictly increasing in both prefix sums and indices.↵
↵
↵
Indices are inserted from left to right
↵
↵
### Theorem↵
↵
For every endpoint $
↵
↵
All feasible stored prefix sums
↵
$$$↵
P_j\leq P_i-K↵
$$$↵
↵
↵
↵
↵
Taking the minimum over all endpoints therefore gives the globally shortest valid subarray.
↵
---
↵
## Implementation↵
↵
```cpp↵
for (int i = 0; i <
while (!a.empty() && a.back().first >= p[i]) {↵
a.pop_back();↵
}↵
↵
a.push_back({p[i], i});↵
↵
if (i
↵
int p
a.begin(),↵
a.end(),↵
make_pair(p[i] - k, i)↵
) - a.begin() - 1;↵
↵
if (p
↵
int l = a[p1].second;↵
ans = min(ans, i -
}↵
}↵
```↵
↵
Here, `p` is the prefix
↵
$$$↵
\left(P_j,j\right).↵
$$$
↵
Since the original problem has
↵
$$$↵
$$$↵
↵
---
↵
## Complexity↵
↵
Each prefix sum is inserted once and removed at most once
↵
We perform one binary search for every prefix sum,
↵
$$$↵
$$$
↵
The memory complexity is
↵
$$$↵
O(n).↵
$$$↵
↵
---
↵
## Final
↵
The important object is not really a stack or a deque. It is the set of non-dominated prefix states.↵
↵
A state
↵
$$$↵
\left(P_x,x\right)↵
$$$↵
↵
is dominated by↵
↵
$$$↵
\left(P_y,y\right)↵
$$$↵
↵
whenever↵
↵
$$$↵
P_y\leq P_x↵
$$$↵
↵
and↵
↵
$$$↵
y>x.↵
$$$
↵
The second state is simultaneously:↵
↵
* easier to satisfy
* better for minimizing the answer
↵
Maintaining only non-dominated states creates a monotone frontier increasing in both prefix sum and index.↵
↵
The classical deque solution exploits the same dominance relation to obtain
↵




