[LeetCode] Minimum Operations to Collect Elements

2869. Minimum Operations to Collect Elements

You are given an array nums of positive integers and an integer k.

In one operation, you can remove the last element of the array and add it to your collection.

Return the minimum number of operations needed to collect elements 1, 2, ..., k.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int minOperations(vector<int>& nums, int k) {
vector<int> has(k+1);
int res = 0;
while(nums.size()) {
int x = nums.back(); nums.pop_back();
if(1 <= x and x <= k) has[x] = 1;
bool ok = true;
for(int i = 1; i <= k; i++) ok &= has[i];
res += 1;
if(ok) return res;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/10/01/PS/LeetCode/minimum-operations-to-collect-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.