Skip to content

Commit 61eff26

Browse files
author
Ayush Singh
committed
Add Day-08 Mathematics solution for Sasha and the Apartment Purchase
1 parent d0094cd commit 61eff26

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""
2+
Problem: B. Sasha and the Apartment Purchase
3+
Link: https://codeforces.com/contest/2098/problem/B
4+
5+
Short Problem Statement:
6+
There are n bars located on a street at given house numbers.
7+
At most k bars can close.
8+
For a house x, define f(x) as the sum of distances from x to all open bars.
9+
Sasha can buy a house x if it is possible to close at most k bars such that
10+
f(x) is minimal among all houses.
11+
The task is to count how many different houses Sasha can potentially buy.
12+
13+
Approach:
14+
The sum of absolute distances is minimized at the median.
15+
After closing at most k bars, the number of remaining bars is m = n - k.
16+
For all subsets of size m, the possible medians form a continuous range.
17+
After sorting the bar positions:
18+
- The minimum possible median is at index (m - 1) // 2
19+
- The maximum possible median is at index (n - m) + (m // 2)
20+
Any integer house number between these two values (inclusive) is valid.
21+
The answer is the length of this interval.
22+
23+
Time Complexity:
24+
O(n log n) per test case due to sorting.
25+
26+
Space Complexity:
27+
O(n)
28+
29+
Example:
30+
Input:
31+
4 0
32+
1 2 3 4
33+
34+
Output:
35+
2
36+
37+
Submission Link:
38+
https://codeforces.com/contest/2098/submission/356283081
39+
"""
40+
41+
import sys
42+
input = sys.stdin.readline
43+
44+
t = int(input())
45+
46+
for _ in range(t):
47+
n, k = map(int, input().split())
48+
a = list(map(int, input().split()))
49+
50+
a.sort()
51+
52+
m = n - k
53+
54+
left_index = (m - 1) // 2
55+
right_index = (n - m) + (m // 2)
56+
57+
result = a[right_index] - a[left_index] + 1
58+
print(result)

0 commit comments

Comments
 (0)