2195. Append K Integers With Minimal Sum
Description
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 <= 105
1 <= nums[i] <= 109
1 <= k <= 108
Solutions
Solution 1: Sorting + Greedy + Mathematics
We can add two sentinel nodes to the array, which are \(0\) and \(2 \times 10^9\).
Then we sort the array. For any two adjacent elements \(a\) and \(b\) in the array, the integers in the interval \([a+1, b-1]\) do not appear in the array, and we can add these integers to the array.
Therefore, we traverse the adjacent element pairs \((a, b)\) in the array from small to large. For each adjacent element pair, we calculate the number of integers \(m\) in the interval \([a+1, b-1]\). The sum of these \(m\) integers is \(\frac{m \times (a+1 + a+m)}{2}\). We add this sum to the answer and subtract \(m\) from \(k\). If \(k\) is reduced to \(0\), we can stop the traversal and return the answer.
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(\log n)\). Where \(n\) is the length of the array.
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|