You are given a 0-indexed array nums consisting of positive integers, representing targets on a number line. You are also given an integer space.
You have a machine which can destroy targets. Seeding the machine with some nums[i] allows it to destroy all targets with values that can be represented as nums[i] + c * space, where c is any non-negative integer.
You want to destroy the maximum number of targets in nums.
Return _theminimum value of _nums[i]you can seed the machine with to destroy the maximum number of targets.
Input: nums =[3,7,8,1,1,5], space =2Output: 1Explanation: If we seed the machine with nums[3], then we destroy all targets equal to 1,3,5,7,9,...In thiscase, we would destroy 5 total targets(all except for nums[2]).It is impossible to destroy more than 5 targets, so we return nums[3].
Input: nums =[1,3,5,2,4,6], space =2Output: 1Explanation: Seeding the machine with nums[0], or nums[3] destroys 3 targets.It is not possible to destroy more than 3 targets.Since nums[0]is the minimal integer that can destroy 3 targets, we return1.
Targets that can be destroyed by the same seed must have the same remainder when divided by space. So, group numbers by their remainder modulo space and pick the group with the most elements. Among all possible seeds in that group, choose the smallest number.
classSolution {
fundestroyTargets(nums: IntArray, space: Int): Int {
val cnt = mutableMapOf<Int, Int>()
val mn = mutableMapOf<Int, Int>()
for (x in nums) {
val r = x % space
cnt[r] = cnt.getOrDefault(r, 0) + 1 mn[r] = minOf(mn.getOrDefault(r, x), x)
}
var mx = 0var ans = Int.MAX_VALUE
for (r in cnt.keys) {
val c = cnt[r]!!if (c > mx || (c == mx && mn[r]!! < ans)) {
mx = c
ans = mn[r]!! }
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defdestroyTargets(self, nums: list[int], space: int) -> int:
cnt: dict[int, int] = {}
mn: dict[int, int] = {}
for x in nums:
r = x % space
cnt[r] = cnt.get(r, 0) +1 mn[r] = min(mn.get(r, x), x)
mx =0 ans = float('inf')
for r in cnt:
c = cnt[r]
if c > mx or (c == mx and mn[r] < ans):
mx = c
ans = mn[r]
return ans