掘金.寻找最大葫芦(简单06)

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.找到最大的组合

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值