贪心
贪心
1个维度【生活常识】
135. 分发糖果
class Solution {
public boolean lemonadeChange(int[] bills) {
int[] arr = new int[2];
for (int bill : bills) {
if (bill == 5){
arr[0]++;
}else if (bill == 10){
if (arr[0] > 0){
arr[0]--;
arr[1]++;
}else {
return false;
}
}else { // 20【fw:不会进行收集】
if (arr[1] > 0){ // 有 10 块
arr[1]--;
if (arr[0] > 0){
arr[0]--;
}else {
return false;
}
}else { // 没有 10 块钱
if (arr[0] >= 3){
arr[0] -= 3;
}else {
return false;
}
}
}
}
return true;
}
}
2个维度【要分别考虑:挑选合适的】
406. 根据身高重建队列
先身高,同时 count 小的在前 ====> 保证当前坐标的前方都是比自己大于等于的 ===> 然后再去一点点微调整
class Solution {
public int[][] reconstructQueue(int[][] people) {
List<man> list = new ArrayList<>();
for (int[] person : people) {
list.add(new man(person[0], person[1]));
}
Collections.sort(list, (o1, o2) -> {
if (o1.height != o2.height) {
return o2.height - o1.height; // 身高大的在前
}
return o1.count - o2.count; // count 小的在前
});
List<man> men = new ArrayList<>();
int[][] arr = new int[people.length][2];
for (int i = 0; i < arr.length; i++) {
man man = list.get(i);
if (man.count == i){
men.add(man);
}else {
men.add(man.count, man);
}
}
for (int i = 0; i < arr.length; i++) {
man man = men.get(i);
arr[i][0] = man.height;
arr[i][1] = man.count;
}
return arr;
}
}
class man{
int height;
int count;
public man(int height, int count) {
this.height = height;
this.count = count;
}
}
OD 高效的任务规划【按照运行时间降序,(配置时间(累加) + 运行时间)取 max】
import java.util.Scanner;
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = Integer.parseInt(in.nextLine());
for (int i = 0; i < count; i++) {
int temp = Integer.parseInt(in.nextLine());
List<machine> list = new ArrayList<>();
for (int j = 0; j < temp; j++) {
String[] split = in.nextLine().split(" ");
int time1 = Integer.parseInt(split[0]);
int time2 = Integer.parseInt(split[1]);
list.add(new machine(time1, time2));
}
Collections.sort(list, (o1, o2) -> o2.time2 - o1.time2); // 1. 按照运行时间降序
int res = 0;
int config_time = 0;
for (int j = 0; j < list.size(); j++) {
machine machine = list.get(j);
config_time += machine.time1; // 2. 配置时间累加
res = Math.max(res, config_time + machine.time2); // 3. 取 max
}
System.out.println(res);
}
}
}
class machine{
int time1;
int time2;
public machine(int time1, int time2) {
this.time1 = time1;
this.time2 = time2;
}
}