import
java.util.*;
class
Pair
implements
Comparable<Pair>
{
public
int
first, second;
public
Pair(
int
a,
int
b)
{
first = a;
second = b;
}
@Override
public
int
compareTo(Pair other)
{
if
(
this
.first == other.first)
return
this
.second - other.second;
return
this
.first - other.first;
}
}
class
GFG
{
static
int
findInd(ArrayList<Pair> preSum,
int
n,
int
val)
{
int
l =
0
;
int
h = n -
1
;
int
mid;
int
ans = -
1
;
while
(l <= h) {
mid = (l + h) /
2
;
if
(preSum.get(mid).first <= val) {
ans = mid;
l = mid +
1
;
}
else
h = mid -
1
;
}
return
ans;
}
static
int
LongestSub(
int
[] arr,
int
n,
int
x)
{
int
i;
for
(i =
0
; i < n; i++)
arr[i] -= x;
int
maxlen =
0
;
ArrayList<Pair> preSum =
new
ArrayList<Pair>();
int
sum =
0
;
int
[] minInd =
new
int
[n];
for
(i =
0
; i < n; i++) {
sum = sum + arr[i];
preSum.add(
new
Pair(sum, i));
}
Collections.sort(preSum);
minInd[
0
] = preSum.get(
0
).second;
for
(i =
1
; i < n; i++) {
minInd[i] = Math.min(minInd[i -
1
], preSum.get(i).second);
}
sum =
0
;
for
(i =
0
; i < n; i++) {
sum = sum + arr[i];
if
(sum >=
0
)
maxlen = i +
1
;
else
{
int
ind = findInd(preSum, n, sum);
if
(ind != -
1
&& minInd[ind] < i)
maxlen = Math.max(maxlen, i - minInd[ind]);
}
}
return
maxlen;
}
public
static
void
main(String[] args)
{
int
[] arr = { -
2
,
1
,
6
, -
3
};
int
n = arr.length;
int
x =
3
;
System.out.println(LongestSub(arr, n, x));
}
}