T1、分发饼干
假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
class Solution {
public int findContentChildren(int[] g, int[] s) {
//定义孩子与饼干
int child = 0;
int cookie = 0;
//将孩子所需大小及饼干大小进行排序
Arrays.sort(g);
Arrays.sort(s);
while(child < g.length && cookie < s.length){
//当饼干大小满足(>=)孩子胃口大小时,孩子满足的数量+1
if(g[child] <= s[cookie]){
child++;
}
cookie++;
}
return child;
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/2a1f2f9c0b81ff94168318d1517f378f.png)
T2、心算挑战
「力扣挑战赛」心算项目的挑战比赛中,要求选手从 N 张卡牌中选出 cnt 张卡牌,若这 cnt 张卡牌数字总和为偶数,则选手成绩「有效」且得分为 cnt 张卡牌数字总和。给定数组 cards 和 cnt,其中 cards[i] 表示第 i 张卡牌上的数字。 请帮参赛选手计算最大的有效得分。若不存在获取有效得分的卡牌方案,则返回 0。
class Solution {
public int maxmiumScore(int[] cards, int cnt) {
//将数组cards进行排序
Arrays.sort(cards);
int sum = 0;
int len = cards.length - 1;
//取最后cnt位最大的数,求和,如果是偶数就直接return
while(cnt > 0){
sum += cards[len--];
cnt--;
}
if(sum % 2 == 0){
return sum;
}
//如果不是偶数,继续进行
for(int i = len; i >= 0; i--){
for(int j = len + 1; j < cards.length; j++){
sum -= cards[j];
sum += cards[i];
if(sum % 2 == 0){
return sum;
}
//如果sum不是偶数,则复原继续进行运算
sum -= cards[i];
sum += cards[j];
}
}
//不存在获取有效得分的方案,返回0
return 0;
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/cb3a67b08f78f087166b2a9b41fd59a0.png)