牛客网 2018校招真题 爱奇艺 字符串价值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32767041/article/details/86498403

Description

牛客网 2018校招真题 字符串价值

Solving Ideas

要使一组数字的平方和最小,只需每次对最大数减1

Time complexity : O ( k ) O(k)
Space complexity : O ( 1 ) O(1)

Solution

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author wylu
 */
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int[] counts = new int[26];
        for (char ch : br.readLine().toCharArray()) counts[ch - 'a']++;
        int k = Integer.parseInt(br.readLine());

        while ((k--) != 0) {
            //每次最大值减1,最终可使总价值达到最小
            int maxIdx = 0;
            for (int i = 1; i < 26; i++) {
                if (counts[i] > counts[maxIdx]) maxIdx = i;
            }
            counts[maxIdx]--;
        }

        int res = 0;
        for (int i = 0; i < 26; i++) res += counts[i] * counts[i];
        System.out.println(res);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_32767041/article/details/86498403