[LeetCode] Shortest Impossible Sequence of Rolls

2350. Shortest Impossible Sequence of Rolls

You are given an integer array rolls of length n and an integer k. You roll a k sided dice numbered from 1 to k, n times, where the result of the ith roll is rolls[i].

Return the length of the shortest sequence of rolls that cannot be taken from rolls.

A sequence of rolls of length len is the result of rolling a k sided dice len times.

Note that the sequence taken does not have to be consecutive as long as it is in order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution {
int fenwick[101010] = {};
void update(int n, int v) {
while(n < 101010) {
fenwick[n] += v;
n += n & -n;
}
}
int query(int n) {
int res = 0;
while(n) {
res += fenwick[n];
n -= n & -n;
}
return res;
}
public:
int shortestSequence(vector<int>& A, int k) {
vector<int> mp(k+1,1);
update(1,k);

for(int i = A.size() - 1; i >= 0; i--) {
int now = A[i];
int level = mp[now];
int sum = query(level - 1);

if(sum) continue;

mp[now] = level + 1;
update(level,-1);
update(level + 1, 1);
}

return *min_element(begin(mp)+1, end(mp));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/24/PS/LeetCode/shortest-impossible-sequence-of-rolls/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.