[LeetCode] Minimum Consecutive Cards to Pick Up

2260. Minimum Consecutive Cards to Pick Up

You are given an integer array cards where cards[i] represents the value of the ith card. A pair of cards are matching if the cards have the same value.

Return the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

class Solution {
public:
int minimumCardPickup(vector<int>& c) {
unordered_map<int, vector<int>> mp;
int n = c.size(), res = INT_MAX;
for(int i = 0; i < n; i++) {
mp[c[i]].push_back(i);
}
for(auto& [_, v] : mp) {
for(int i = 0; i < v.size() - 1; i++) {
res = min(res, v[i + 1] - v[i] + 1);
}
}
return res == INT_MAX ? -1 : res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/01/PS/LeetCode/minimum-consecutive-cards-to-pick-up/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.