leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

2462.cpp (757B)


      1 class Solution {
      2   public:
      3     long long totalCost(vector<int> &costs, int k, int candidates) {
      4         priority_queue<int, vector<int>, greater<int>> pq1, pq2;
      5         int i = 0, j = costs.size() - 1;
      6         long long res = 0;
      7         while (k--) {
      8             while (pq1.size() < candidates && i <= j)
      9                 pq1.push(costs[i++]);
     10             while (pq2.size() < candidates && j >= i)
     11                 pq2.push(costs[j--]);
     12             int a = pq1.size() > 0 ? pq1.top() : INT_MAX;
     13             int b = pq2.size() > 0 ? pq2.top() : INT_MAX;
     14             if (a <= b) {
     15                 res += a;
     16                 pq1.pop();
     17             } else {
     18                 res += b;
     19                 pq2.pop();
     20             }
     21         }
     22         return res;
     23     }
     24 };