Record brushing questions (leetcode——1431 has the most candy children)

**Title: Give you an array of candies and an integer extraCandies, where candies[i] represents the number of candies owned by the i-th child.
For each child, check whether there is a plan. After allocating extra Candies to the children, this child has the most candies. Note that multiple children are allowed to have the maximum number of candies at the same time.

Example 1:
Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true]
Explanation:
Child 1 has 2 candies, if he gets all the extras Candies (3), then he has 5 candies in total, and he will become the child with the most candies.
Child 2 has 3 candies. If he gets at least 2 extra candies, then he will be the child with the most candies.
Child 3 has 5 candies, and he is already the child with the most candies.
Child 4 has 1 candy. Even if he gets all the extra candies, he only has 4 candies and cannot be the child with the most candies.
Child 5 has 3 candies. If he gets at least 2 extra candies, then he will be the child with the most candies.
Example 2:
Input: candies = [4,2,1,1,2], extraCandies = 1
Output: [true,false,false,false,false]
Explanation: There is only 1 extra candies, so no matter who the extra candies are given, Only child 1 can be the child with the most candies.
Example 3:
Input: candies = [12,1,12], extraCandies = 10
Output: [true,false,true]
Source: LeetCode
Link: https://leetcode-cn.com/problems/kids- with-the-greatest-number-of-candies
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source. **
Question-solving idea: find the maximum value in the array, add extra candy to each item, traverse the array again to find the item greater than or equal to the maximum value and set it to true.

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
bool* kidsWithCandies(int* candies, int candiesSize, int extraCandies, int* returnSize){
    
    
    int max_one = candies[0];
    bool *ret = (bool*)malloc(sizeof(bool)*candiesSize);
    for(int i=0;i<candiesSize;i++){
    
    
        max_one = candies[i]>max_one?candies[i]:max_one;
        candies[i]=candies[i]+extraCandies;
    }
    for(int i=0;i<candiesSize;i++){
    
    
        ret[i]=candies[i]>=max_one?true:false;
    }
    *returnSize=candiesSize;
    return ret;
}

Guess you like

Origin blog.csdn.net/lthahaha/article/details/106504469