You are given an integer array nums and an integer k. Append kunique positive integers that do not appear in nums to nums such that the resulting total sum is minimum.
Input: nums =[1,4,25,10,25], k =2Output: 5Explanation: The two unique positive integers that do not appear in nums which we append are 2 and 3.The resulting sum of nums is1+4+25+10+25+2+3=70, which is the minimum.The sum of the two integers appended is2+3=5, so we return5.
Example 2:
1
2
3
4
5
Input: nums =[5,6], k =6Output: 25Explanation: 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 is5+6+1+2+3+4+7+8=36, which is the minimum.The sum of the six integers appended is1+2+3+4+7+8=25, so we return25.
To minimize the sum, we should append the smallest missing positive integers not in nums. By sorting and scanning for gaps, we can efficiently find and sum the first k missing numbers.
classSolution {
public:longlong minimalKSum(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
longlong ans =0, cur =1;
for (int x : nums) {
if (x < cur) continue;
if (k ==0) break;
longlong cnt = min((longlong)x - cur, (longlong)k);
ans += (cur + cur + cnt -1) * cnt /2;
k -= cnt;
cur = x +1;
}
if (k >0) {
ans += (cur + cur + k -1) * k /2;
}
return ans;
}
};
classSolution {
publiclongminimalKSum(int[] nums, int k) {
Arrays.sort(nums);
long ans = 0, cur = 1;
for (int x : nums) {
if (x < cur) continue;
if (k == 0) break;
long cnt = Math.min(x - cur, (long)k);
ans += (cur + cur + cnt - 1) * cnt / 2;
k -= cnt;
cur = x + 1;
}
if (k > 0) {
ans += (cur + cur + k - 1) * k / 2;
}
return ans;
}
}
classSolution {
funminimalKSum(nums: IntArray, k: Int): Long {
nums.sort()
var ans = 0Lvar cur = 1Lvar rem = k
for (x in nums) {
if (x < cur) continueif (rem ==0) breakval cnt = minOf(x - cur, rem.toLong())
ans += (cur + cur + cnt - 1) * cnt / 2 rem -= cnt.toInt()
cur = x.toLong() + 1 }
if (rem > 0) {
ans += (cur + cur + rem - 1) * rem / 2 }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defminimalKSum(self, nums: list[int], k: int) -> int:
nums = sorted(set(nums))
ans =0 cur =1for x in nums:
if x < cur:
continue cnt = min(x - cur, k)
ans += (cur + cur + cnt -1) * cnt //2 k -= cnt
cur = x +1if k ==0:
breakif k >0:
ans += (cur + cur + k -1) * k //2return ans
impl Solution {
pubfnminimal_k_sum(mut nums: Vec<i32>, mut k: i32) -> i64 {
nums.sort_unstable();
nums.dedup();
letmut ans =0i64;
letmut cur =1i64;
for&x in&nums {
if x asi64< cur { continue; }
let cnt = (x asi64- cur).min(k asi64);
ans += (cur + cur + cnt -1) * cnt /2;
k -= cnt asi32;
cur = x asi64+1;
if k ==0 { break; }
}
if k >0 {
ans += (cur + cur + k asi64-1) * k asi64/2;
}
ans
}
}