carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2558: Take Gifts From the Richest Pile #418

Open carloscn opened 10 months ago

carloscn commented 10 months ago

Description

You are given an integer array gifts denoting the number of gifts in various piles. Every second, you do the following:

Choose the pile with the maximum number of gifts. If there is more than one pile with the maximum number of gifts, choose any. Leave behind the floor of the square root of the number of gifts in the pile. Take the rest of the gifts. Return the number of gifts remaining after k seconds.

Example 1:

Input: gifts = [25,64,9,4,100], k = 4 Output: 29 Explanation: The gifts are taken in the following way:

Example 2:

Input: gifts = [1,1,1,1], k = 4 Output: 4 Explanation: In this case, regardless which pile you choose, you have to leave behind 1 gift in each pile. That is, you can't take any pile with you. So, the total gifts remaining are 4.

Constraints:

1 <= gifts.length <= 103 1 <= gifts[i] <= 109 1 <= k <= 103

carloscn commented 10 months ago

Analysis

static int64_t pick_gifts(int32_t* gifts, size_t gifts_size, int32_t k)
{
    int64_t ret = 0;

    UTILS_CHECK_PTR(gifts);
    UTILS_CHECK_LEN(gifts_size);
    UTILS_CHECK_LEN(k);

    int32_t i = 0;
    while (i < k) {
        size_t max_index = 0;
        int32_t max_value = INT32_MIN;
        for (size_t j = 0; j < gifts_size; j ++) {
            max_value = (max_value > gifts[j])?
                        (max_value):
                        (max_index = j, gifts[j]);
        }
        gifts[max_index] = (int64_t)utils_sqrt((double)max_value);
        i ++;
    }

    for (size_t j = 0; j < gifts_size; j ++) {
        ret += gifts[j];
    }

finish:
    return ret;
}
carloscn commented 10 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1172030 https://github.com/carloscn/structstudy/commit/cdfaf4b6f02301620f4798ecac2ea1274a13f381