Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 1962. Remove Stones to Minimize the Total

Rain Hu

1962. Remove Stones to Minimize the Total


一、題目

You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times:
Choose any piles[i] and remove floor(piles[i] / 2) stones from it. Notice that you can apply the operation on the same pile more than once.
Return the minimum possible total number of stones remaining after applying the k operations.
floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down).

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. Heap (Priority Queue)

int minStoneSum(vector<int>& piles, int k) {
    priority_queue<int> pq;
    int res = 0;
    for (const auto& pile : piles) {
        pq.push(pile);                  // 先將所有堆都推到 priority queue 上
        res += pile;                    // 順便將原本的石頭總數算出來
    }
    while (k--) {
        int curr = pq.top(); pq.pop();
        int loss = curr >> 1;           // 當下的 max heap 的堆頂除於 2 即為當下可以一次取到最多的石頭
        pq.push(curr - loss);           // 將取完的堆放回 priority queue 上
        res -= loss;                    // 將總數減掉拿掉的石頭
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[C#] Yield Return
Next
[LeetCode] 2279. Maximum Bags With Full Capacity of Rocks