import java.util.*;
public class Main {
public static int[] solution(int n, int max, int[] array) {
int a = 0,b = 0;
for (int i = 0; i < n; i++) {
if(array[i] == 1)array[i] = 14;
}
//1.给数组排序
Arrays.sort(array);
//2.按照从大到小的顺序存入map中
LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>();
for (int i = n-1; i >= 0 ; i--) {
if(map.containsKey(array[i])){
map.put(array[i],map.get(array[i])+1);
} else {
map.put(array[i],1);
}
}
//3.删除map中value小于2的键值对
map.entrySet().removeIf(entry -> entry.getValue() < 2); System.out.println(map);
//4.找到最大的组合
all:for (Integer key1 : map.keySet()) {
Integer value1 = map.get(key1);
if(value1 < 3)continue;
for (Integer key2 : map.keySet()) {
if((key1 * 3 + key2 * 2 <= max) && (key1 != key2) &&(key1 != 14)&&(key2 != 14)){
a = key1;
b = key2;
break all;
} else if ((key1 == 14)||(key2 == 14)) {
if(key1 == 14)key1 = 1;
if(key2 == 14)key2 = 1;
if((key1 * 3 + key2 * 2 <= max) && (key1 != key2)){
a = key1;
b = key2;
break all;
}
}
}
}
System.out.println(a + " " + b);
return new int[]{a, b};
}
public static void main(String[] args) {
// Add your test cases here
System.out.println(java.util.Arrays.equals(solution(9, 34, new int[]{6, 6, 6, 8, 8, 8, 5, 5, 1}), new int[]{8, 5}));
System.out.println(java.util.Arrays.equals(solution(9, 37, new int[]{9, 9, 9, 9, 6, 6, 6, 6, 13}), new int[]{6, 9}));
System.out.println(java.util.Arrays.equals(solution(9, 40, new int[]{1, 11, 13, 12, 7, 8, 11, 5, 6}), new int[]{0, 0}));
}
}
思路如下:
1.给数组排序
2.按照从大到小的顺序存入map中
3.删除map中value小于2的键值对
4.找到最大的组合