Home [LeetCode] 1431. Kids With the Greatest Number of Candies (擁有最多糖果的孩子)
Post
Cancel

[LeetCode] 1431. Kids With the Greatest Number of Candies (擁有最多糖果的孩子)

1431. 擁有最多糖果的孩子

1431. Kids With the Greatest Number of Candies

There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.

Return a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.

Note that multiple kids can have the greatest number of candies.

給你一個陣列 candies 和一個整數 extraCandies ,其中 candies[i] 代表第 i 個孩子擁有的糖果數目。

對每個孩子,檢查是否存在一種方案,將額外的 extraCandies 個糖果分配給孩子們之後,此孩子有 最多 的糖果。注意,允許有多個孩子同時擁有 最多 的糖果數目。

Example 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Input: candies = [2,3,5,1,3], extraCandies = 3
Output: [true,true,true,false,true] 
Explanation: If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.

孩子 1 有 2 個糖果,如果他得到所有額外的糖果(3個),那麼他總共有 5 個糖果,他將成為擁有最多醣果的孩子。
孩子 2 有 3 個糖果,如果他得到至少 2 個額外糖果,那麼他將成為擁有最多醣果的孩子。
孩子 3 有 5 個糖果,他已經是擁有最多醣果的孩子。
孩子 4 有 1 個糖果,即使他得到所有額外的糖果,他也只有 4 個糖果,無法成為擁有糖果最多的孩子。
孩子 5 有 3 個糖果,如果他得到至少 2 個額外糖果,那麼他將成為擁有最多醣果的孩子。

Example 2:

1
2
3
4
5
6
Input: candies = [4,2,1,1,2], extraCandies = 1
Output: [true,false,false,false,false] 
Explanation: There is only 1 extra candy.
Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.

只有 1 個額外糖果,所以不管額外糖果給誰,只有孩子 1 可以成為擁有糖果最多的孩子

Example 3:

1
2
Input: candies = [12,1,12], extraCandies = 10
Output: [true,false,true]

解題實作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System.Collections.Generic;
using System.Linq;

public class Solution {
    public IList<bool> KidsWithCandies(int[] candies, int extraCandies) {
        //取得原本糖果的最大值(使用Linq取得陣列中最大值)
        int maxCount = candies.Max();

        //遍歷每個小孩
        IList<bool> list = new List<bool>();
        for(int i = 0; i<candies.Length; i++) {
            //給小孩加上額外的糖果,但不能超過maxCount
            candies[i] = (candies[i] + extraCandies > maxCount)? maxCount : candies[i] + extraCandies;
            //檢查擁有最多糖果的小孩
            list.Add((candies[i]==maxCount)? true: false);
        }
        return list;
    }
}
This post is licensed under CC BY 4.0 by the author.