最低成本清空数组

115 阅读1分钟

问题描述

小S正在处理一个包含N个整数的数组A,这些整数的编号从0N-1。他需要通过一系列迭代操作将数组清空。在每次迭代中,小S必须从数组中删除K个值相同的元素,第T次迭代的成本为 T * V,其中V是被删除元素的值。

你的任务是找到清空数组A的最低成本。如果不可能清空数组,则返回-1


测试样例

样例1:

输入:N = 6, K = 2, A = [1, 6, 6, 1, 1, 1]
输出:11

样例2:

输入:N = 4, K = 2, A = [5, 5, 5, 5]
输出:15

样例3:

输入:N = 5, K = 3, A = [2, 2, 2, 2, 2]
输出:-1

我们对数组排下序计算就行


import java.util.*;
public class Main {
     public static int solution(int N, int K, int[] A) {
        //先对A进行逆序排序
        Arrays.sort(A);
        int tmp,i=0,j=N-1;
        while(i<j){
            tmp=A[i];
            A[i]=A[j];
            A[j]=tmp;
            i++;
            j--;
        }
        //统计他的数量
        List<int[]> simpleMap=new ArrayList<>();//【A的数,这个数的数量】
        int[] mp=new int[]{A[0],1};
        simpleMap.add(mp);
        for(i=1;i<N;i++){
            if(A[i]==A[i-1]){
                simpleMap.get(simpleMap.size()-1)[1]++;
            }else{
                mp=new int[]{A[i],1};
                simpleMap.add(mp);
            }
        }
        int res=0,num=1;
        for (int[] ints : simpleMap) {

            if(ints[1]%K!=0){
                return  -1;
            }
            tmp=ints[1]/K;
            for(i=0;i<tmp;i++){
                res+=ints[0]*num;
                num++;
            }

        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(solution(6, 2, new int[]{1, 6, 6, 1, 1, 1}) == 11);
        System.out.println(solution(4, 2, new int[]{5, 5, 5, 5}) == 0);
        System.out.println(solution(5, 3, new int[]{2, 2, 2, 2, 2}) == -1);
    }
}