Skip to content

Commit bfd48cf

Browse files
authored
Create Total Cost to Hire K Workers.cpp
1 parent 61b6d74 commit bfd48cf

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
//2462. Total Cost to Hire K Workers
2+
class Solution
3+
{
4+
public:
5+
long long totalCost(vector<int> &costs, int k, int candidates)
6+
{
7+
int n = costs.size();
8+
9+
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;
10+
vector<bool> check(n,false);
11+
12+
int s=0,e=n-1;
13+
for(int i=0;i<candidates;i++)
14+
{
15+
if(s<=e){
16+
pq.push({costs[i],i});
17+
s=i+1;
18+
}
19+
}
20+
for(int i=n-1;i>=n-candidates;i--)
21+
{
22+
if(s<=e){
23+
pq.push({costs[i],i});
24+
e=i-1;
25+
}
26+
}
27+
28+
long long ans=0;
29+
for(int i=0;i<k;i++){
30+
auto temp1=pq.top();
31+
ans+=temp1.first;
32+
pq.pop();
33+
check[temp1.second]=true;
34+
if(temp1.second<s && s<=e){
35+
pq.push({costs[s],s});
36+
s++;
37+
}
38+
else if(temp1.second>e && s<=e){
39+
pq.push({costs[e],e});
40+
e--;
41+
}
42+
}
43+
return ans;
44+
}
45+
};

0 commit comments

Comments
 (0)