import
java.util.*;
public
class
MinCostPath {
public
static
class
Pair<K, V> {
private
final
K key;
private
final
V value;
public
Pair(K key, V value)
{
this
.key = key;
this
.value = value;
}
public
K getKey() {
return
key; }
public
V getValue() {
return
value; }
}
public
static
int
minCostPath(
int
n,
int
m,
int
[][] arr)
{
List<Pair<Integer, Integer> > res
=
new
ArrayList<>();
for
(
int
i =
0
; i < n; i++) {
for
(
int
j =
0
; j < m; j++) {
res.add(
new
Pair<>(arr[i][j], j));
}
}
Collections.sort(
res,
new
Comparator<Pair<Integer, Integer> >() {
@Override
public
int
compare(
Pair<Integer, Integer> p1,
Pair<Integer, Integer> p2)
{
return
p1.getKey().compareTo(
p2.getKey());
}
});
Map<Integer, Integer> hsh =
new
HashMap<>();
Deque<Integer> dq =
new
ArrayDeque<>();
int
i =
0
, ans = Integer.MAX_VALUE;
for
(
int
j =
0
; j < res.size(); j++) {
hsh.put(
res.get(j).getValue(),
hsh.getOrDefault(res.get(j).getValue(),
0
)
+
1
);
while
(hsh.size() == m) {
hsh.put(res.get(i).getValue(),
hsh.get(res.get(i).getValue()) -
1
);
if
(hsh.get(res.get(i).getValue()) ==
0
) {
hsh.remove(res.get(i).getValue());
}
ans = Math.min(ans,
res.get(j).getKey()
- res.get(i).getKey());
i++;
}
}
return
ans;
}
public
static
void
main(String[] args)
{
int
N =
3
;
int
M =
3
;
int
[][] arr
= { {
1
,
2
,
3
}, {
1
,
2
,
3
}, {
2
,
1
,
1
} };
System.out.println(minCostPath(N, M, arr));
}
}