Leetcode 2305 Solution

This article provides solution to leetcode question 2305 (append-k-integers-with-minimal-sum)

https://leetcode.com/problems/append-k-integers-with-minimal-sum

Solution

class Solution:
    def minimalKSum(self, nums: List[int], k: int) -> int:
        nums = [0] + sorted(nums) + [sys.maxsize]

        print(nums)

        ans = 0
        for i in range(len(nums) - 1):
            if nums[i] == nums[i + 1]:
                continue

            if k <= nums[i + 1] - nums[i] - 1:
                ans += (nums[i] + 1 + nums[i] + k) * k // 2
                break
            else:
                ans += (nums[i] + nums[i + 1]) * (nums[i + 1] - nums[i] - 1) // 2
                k -= nums[i + 1] - nums[i] - 1

        return ans