贪心算法:
简单易行,局部最优解->全局最优解 (与正确结果非常相近)
Leetcode 455. 分发饼干
假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。
对每个孩子 i,都有一个胃口值 g[i],这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j,都有一个尺寸 s[j] 。如果 s[j] >= g[i],我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
class Solution {
public int findContentChildren(int[] g, int[] s) {
//孩子的数量
int number = 0;
//满足最小孩子的最小饼干数,本次可以匹配的索引,所以下一次要+1
int index = 0;
//根据题目和分配,两个数组从小到大排列
//Arrays.sort(arr);
//Sorts arr[] in descending order
//Arrays.sort(arr, Collections.reverseOrder());
Arrays.sort(g);
Arrays.sort(s);
//base case
if(s.length == 0 || g.length == 0){
return 0;
}
//for循环,孩子胃口从小到大,饼干值从小到大,饼干从index开始,每次更新index的值,减少循环量以及避免再次选中重复饼干
for(int i = 0; i < g.length; i++){
for(int j = index; j < s.length; j++){
if(g[i] <= s[j]){
//index加1,
index = j + 1;
number++;
//跳出内层循环
break;
}
//如果孩子胃口比饼干大小还大,那么执行j++
}
}
return number;
}
}
Leetcode 122 买卖股票
给定一个数组 prices ,其中 prices[i] 是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
//只有一天价格,返回0;
if(prices.length==1){
return 0;
}
//(fence post problem)要么单独拎前两个出来,要么单独拎后两个出来。
if(prices[0]<prices[1]){
profit = prices[1]-prices[0];
}
for(int i = 2; i < prices.length; i++){
if(prices[i-1]<prices[i]){
profit += prices[i] - prices[i-1];
}
}
return profit;
}
}
for(int i=1;i<=prices.length-1;i++)
{
if(prices[i]>prices[i-1])
{
ans+=prices[i]-prices[i-1];
}
}