Append K Integers With Minimal Sum Problem
Description
LeetCode Problem 2195.
You are given an integer array nums and an integer k. Append k unique positive integers that do not appear in nums to nums such that the resulting total sum is minimum.
Return the sum of the k integers appended to nums.
Example 1:
Input: nums = [1,4,25,10,25], k = 2
Output: 5
Explanation: The two unique positive integers that do not appear in nums which we append are 2 and 3.
The resulting sum of nums is 1 + 4 + 25 + 10 + 25 + 2 + 3 = 70, which is the minimum.
The sum of the two integers appended is 2 + 3 = 5, so we return 5.
Example 2:
Input: nums = [5,6], k = 6
Output: 25
Explanation: The six unique positive integers that do not appear in nums which we append are 1, 2, 3, 4, 7, and 8.
The resulting sum of nums is 5 + 6 + 1 + 2 + 3 + 4 + 7 + 8 = 36, which is the minimum.
The sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return 25.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^91 <= k <= 10^8
Solution
Approach: Sort + greedy + arithmetic series
Add two sentinels to the array, 0 and 2 * 10^9, and sort it. Between two neighbouring values a < b the integers a+1 .. b-1 are all missing from the array, so they are the candidates we may append. Appending the smallest unused integers is optimal, so we walk through the neighbouring pairs from small to large.
For each pair, take m = min(k, b - a - 1) integers (never fewer than 0). Their sum is m * (a + 1 + a + m) / 2; add it to the answer and subtract m from k. Once k reaches 0 we can stop.
Complexity: O(n log n) time, O(log n) extra space for the sort.
class Solution:
def minimalKSum(self, nums: List[int], k: int) -> int:
nums.extend([0, 2 * 10**9])
nums.sort()
ans = 0
for a, b in zip(nums, nums[1:]):
m = max(0, min(k, b - a - 1))
ans += (a + 1 + a + m) * m // 2
k -= m
return ans