LeetCode-in-Java

3974. Maximum Total Sum of K Selected Elements

Medium

You are given an integer array nums and two integers k and mul.

Select exactly k elements from nums. Process these elements one by one in any order you choose.

For each selected element, independently choose one of the following:

After processing each selected element, mul decreases by 1, regardless of which option was chosen. The current value of mul may become 0 or negative.

Return an integer denoting the maximum possible total sum.

Example 1:

Input: nums = [6,1,2,9], k = 3, mul = 2

Output: 26

Explanation:

One optimal way:

Example 2:

Input: nums = [3,7,5,2], k = 2, mul = 4

Output: 43

Explanation:

One optimal way:

Example 3:

Input: nums = [4,4], k = 1, mul = 1

Output: 4

Explanation:

One optimal way:

Constraints:

Solution

public class Solution {
    private static final int MAX = 100_000 + 1;

    public long maxSum(int[] nums, int k, int mul) {
        int[] count = new int[MAX];
        int max = nums[0];
        long sum = 0;
        for (int n : nums) {
            max = Math.max(max, n);
            count[n]++;
        }
        while (max >= 0 && k > 0) {
            if (count[max] != 0) {
                int min = Math.min(mul, count[max]);
                min = Math.min(k, min);
                k -= min;
                mul -= min;
                long local =
                        ((long) (mul + min) * (mul + min + 1)) / 2 - ((long) mul * (mul + 1)) / 2;
                sum += local * max;
                if (mul == 0) {
                    count[max] -= min;
                    break;
                }
            }
            max--;
        }
        while (max >= 0 && k > 0) {
            if (count[max] != 0) {
                int min = Math.min(k, count[max]);
                k -= min;
                sum += (long) max * min;
            }
            max--;
        }
        return sum;
    }
}