[LeetCode] Destroy Sequential Targets

2453. Destroy Sequential Targets

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 the minimum value of nums[i] you can seed the machine with to destroy the maximum number of targets.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int destroyTargets(vector<int>& nums, int space) {
int ma = 0, pick = -1;
unordered_map<int, int> freq;
unordered_map<int, int> mi;
for(auto n : nums) {
int now = n % space;
if(!mi.count(now)) mi[now] = n;
mi[now] = min(mi[now], n);
++freq[now];
if(ma < freq[now]) {
ma = freq[now];
pick = mi[now];
} else if(ma == freq[now]) pick = min(pick, mi[now]);
}
return pick;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/30/PS/LeetCode/destroy-sequential-targets/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.