455-Assign Cookies
先对两个数组进行排序,变成从小到大
对g中的每一个数,找到s数组中第一个大于等于g中数的人,删除s中的这个数
class solution455{
public int findContentChildren(int[] g,int[] s) {
int res=0;
Arrays.sort(g);
Arrays.sort(s);
for(int cg:g) {
//对需求较小的孩子找饼干
for(int i=0;i<s.length;i++) {
if(s[i]>=cg) {
res++;
s[i]=-Integer.MAX_VALUE;
break;
}
//如果上一轮中找不到可以满足的饼干,后面需求更大的孩子也不可能满足,直接返回。
return res;
}
}
return res;
}
方法2,贪心思想:优先满足需求因子小的孩子,因为如果较小需求的孩子无法满足,较大的需求不可能被满足
public int findContentChildren2(int[] g,int[] s) {
if(g==null||s==null||g.length==0||s.length==0) {//没有饼干,没有孩子
return 0;
}
int i=0,j=0;
Arrays.sort(g);
Arrays.sort(s);
while(i<g.length&&j<s.length) {
if(g[i]<=s[j]) {
i++;
j++;
}else {
j++;
}
}
return i;
}
}
122-Best Time to Buy and Sell Stock II (121系列问题)
//买卖股票的最佳时机2
//贪心思想,从第一天开始,判断后面是涨价了还是没涨价,只要降价立刻前一天卖出,涨价继续向后判断。
class solution122{
计算每一天买入第二天卖出的话可以得到的利润,存入函数,将所有正数相加就是所能获得的利润
public int maxprofit(int[] prices) {
int res=0;
int length=prices.length;
int [] profit=new int[length-1];
for(int i=0;i<length-1;i++) {
profit[i]=prices[i+1]-prices[i];
}
for(int price:profit) {
if(price>0) {
res+=price;
}
}
return res;
}
}