[LeetCode] Hand of Straights

846. Hand of Straights

Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.

Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
bool isNStraightHand(vector<int>& hand, int groupSize) {
if(hand.size() % groupSize) return false;
map<int, int> remain;
for(auto h : hand) remain[h]++;

while(!remain.empty()) {
auto be = remain.begin();
auto nxt = next(be);
for(int i = 1; i < groupSize and be->second; i++,++nxt) {
if(nxt == remain.end()) return false;
if(nxt->first != be->first + i) return false;
if(nxt->second < be->second) return false;
nxt->second -= be->second;
}
remain.erase(be);

}
return true;

}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/hand-of-straights/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.