File tree Expand file tree Collapse file tree
Problems/Binary-Search/Day-07/sol/Ishan_Raj_Singh Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ """
2+ Approach: Optimized Sliding Window with Divisor Enumeration
3+ Submission Link: https://codeforces.com/contest/1777/submission/356144999
4+ """
5+
6+ def solve_optimized ():
7+ n , m = map (int , input ().split ())
8+ a = list (map (int , input ().split ()))
9+
10+ students = []
11+ for val in a :
12+ divisors = []
13+ i = 1
14+ while i * i <= val :
15+ if val % i == 0 :
16+ if i <= m :
17+ divisors .append (i )
18+ if i != val // i and val // i <= m :
19+ divisors .append (val // i )
20+ i += 1
21+
22+ if divisors :
23+ students .append ((val , divisors ))
24+
25+ if not students :
26+ print (- 1 )
27+ return
28+
29+ students .sort ()
30+
31+ left = 0
32+ ans = float ('inf' )
33+ freq = {}
34+
35+ for right in range (len (students )):
36+ for topic in students [right ][1 ]:
37+ freq [topic ] = freq .get (topic , 0 ) + 1
38+
39+ while len (freq ) == m :
40+ ans = min (ans , students [right ][0 ] - students [left ][0 ])
41+
42+ remove_ok = True
43+ for topic in students [left ][1 ]:
44+ if freq .get (topic , 0 ) == 1 :
45+ remove_ok = False
46+ break
47+
48+ if remove_ok :
49+ for topic in students [left ][1 ]:
50+ freq [topic ] -= 1
51+ if freq [topic ] == 0 :
52+ del freq [topic ]
53+ left += 1
54+ else :
55+ break
56+
57+ print (ans if ans != float ('inf' ) else - 1 )
58+
59+ t = int (input ())
60+ for _ in range (t ):
61+ solve_optimized ()
You can’t perform that action at this time.
0 commit comments