import
java.util.ArrayList;
import
java.util.Collections;
import
java.util.Comparator;
class
GFG {
static
class
Pair {
int
first =
0
;
int
second =
0
;
public
Pair(
int
first,
int
second) {
this
.first = first;
this
.second = second;
}
}
public
static
int
calcEven(ArrayList<Pair> V,
int
N,
int
k) {
if
(k <=
0
|| N ==
0
)
return
-
1
;
Collections.sort(V,
new
Comparator<Pair>() {
@Override
public
int
compare(Pair p1, Pair p2) {
return
p1.first - p2.first;
}
});
int
i, idx =
0
;
for
(i =
1
; i < N; i++) {
if
((V.get(idx).second >= V.get(i).first) || (V.get(i).first == V.get(idx).second +
1
)) {
V.get(idx).second = Math.max(V.get(idx).second, V.get(i).second);
}
else
{
idx++;
V.get(idx).second = V.get(i).second;
V.get(idx).first = V.get(i).first;
}
}
for
(i = idx; i >=
0
; i--) {
int
L = V.get(i).first;
int
R = V.get(i).second;
if
((R &
1
) >
0
) {
int
range = (R - L +
1
) /
2
;
if
(k > range) {
k -= range;
}
else
return
(R -
2
* k +
1
);
}
else
{
int
range = (
int
) Math.ceil((R - L +
1
) /
2
);
if
(k > range) {
k -= range;
}
else
return
(R -
2
* k +
2
);
}
}
return
-
1
;
}
public
static
void
main(String args[]) {
ArrayList<Pair> vec =
new
ArrayList<Pair>();
vec.add(
new
Pair(
12
,
15
));
vec.add(
new
Pair(
3
,
9
));
vec.add(
new
Pair(
2
,
5
));
vec.add(
new
Pair(
20
,
25
));
vec.add(
new
Pair(
16
,
20
));
int
N = vec.size();
int
K =
9
;
System.out.println(calcEven(vec, N, K));
}
}