文章目录
860.柠檬水找零
在20元找零处用到了贪心,贪10元的个数,如果有就先找10元+5元,没有再找三个5元
public class Solution {
public boolean lemonadeChange(int[] bills) {
int five = 0;
int ten = 0;
for (int bill : bills) {
if (bill == 5) five++;//支付5元
else if (bill == 10) {
//支付10元
if (five > 0) {
//如果有5元的,找5元
five--;
ten++;
} else {
//如果没有5元的就无法找零退出
return false;
}
} else {
//支付20元
if (ten > 0 && five > 0) {
//如果有10元和5元的,找10元+5元
ten--;
five--;
} else if (ten == 0 && five >= 3) {
//如果没有10元的有3张及以上5元的
five -= 3;
} else//如果零钱不够,退出
return false;
}
}
return true;
}
}
455.分发饼干
将两个数组进行排序
从最小胃口的孩子和最小的饼干开始比较,如果不满足饼干后移一位,如果满足计数加一,饼干和小孩都后移一位
public class Solution {
public int findContentChildren(int[] g, int[] s) {
Arrays.sort(g);
Arrays.sort(s);
int i = 0;
int j = 0;
int count = 0;
while (i < g.length && j < s.length) {
if (g[i] <= s[j]) {
count++;
i++;
j++;
} else {
j++;
}
}
return count;
}
}
121.买卖股票的最佳时机
遍历数组,如果值小于当前最小值更换当前最小值,如果值大于当前最小值和最小值做差更新最大差
public class Solution {
public int maxProfit(int[] prices) {
if (prices.length == 0) return 0;
int max = 0;
int minPrice = prices[0];
for (int i = 1; i < prices.length; i++) {
if (prices[i] < minPrice) minPrice = prices[i];
else max = Math.max(prices[i] - minPrice, max);
}
return max;
}
}
122.买卖股票的最佳时机II
贪心:如果第二天大于第一天就第一天买第二天卖
public class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for (int i = 0; i < prices.length - 1; i++) {
if (prices[i] < prices[i + 1