Problem · Heap
Sum Max Plus Min After Decrement Operations
Learn this problemProblem statement
You are given an integer array arr and an integer requests.
Repeat the following operation exactly requests times:
- Find the current maximum value and the current minimum value in
arr. - Add their sum to the answer.
- Choose one occurrence of the maximum value and decrease it by 1.
Return the final accumulated answer.
Function
sumMaxPlusMinAfterOperations(arr: int[], requests: int) → longComplete the function sumMaxPlusMinAfterOperations in the editor below.
sumMaxPlusMinAfterOperations has the following parameters:
int[] arr: the initial valuesint requests: the number of operations
Returns
long: the accumulated sum
Examples
Example 1
arr = [1, 2]requests = 2return = 5First add 1 + 2 = 3 and decrement the 2 to 1. Then add 1 + 1 = 2. The total is 5.
Example 2
arr = [3, 3, 3]requests = 1return = 6The current maximum and minimum are both 3, so the answer increases by 6.
Constraints
1 <= arr.length <= 1051 <= arr[i] <= 1090 <= requests <= 109- Each operation decreases one occurrence of the current maximum value by exactly 1.
- Use a wide enough integer type (e.g.,
long) for the accumulated total.