Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 2462. Total Cost to Hire K

Rain Hu

2462. Total Cost to Hire K


一、題目

You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the ith worker. You are also given two integers k and candidates. We want to hire exactly k workers according to the following rules:

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. Heap (Priority Queue)

long long totalCost(vector<int>& costs, int k, int candidates) {
    priority_queue<int, vector<int>, greater<int>> front, end;  // 宣告兩個 min heap
    long long res = 0;
    int cnt = 0;
    int i = 0, j = costs.size()-1;
    front.push(INT_MAX);                                        // 當 min heap 為空時,必定傳回另一個 min heap 的值
    end.push(INT_MAX);
    while (i <= j && cnt < candidates) {
        front.push(costs[i++]);                                 // 左指針移動
        if (i <= j) end.push(costs[j--]);                       // 右指針移動,左右指針相撞,代表已經包含整個數組
        cnt++;
    }
    while (k--) {                                               // 取 k 個數字
        if (front.top() <= end.top()) {
            res += front.top();
            front.pop();
            if (i <= j) front.push(costs[i++]);                 // 左右指針相撞,不再加入新的值
        } else {
            res += end.top();
            end.pop();
            if (i <= j) end.push(costs[j--]);                   // 左右指針相撞,不再加入新的值
        }
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 1544. Make The String Great
Next
[LeetCode] 2461. Maximum Sum of Distinct Subarrays With Length K