Maximize Sum After At Most K Digit Rearrangements Problem
Description
LeetCode Problem 4093.
You are given an integer array nums of length n and an integer k.
In one operation, you may choose any element of nums and rearrange its decimal digits in any order to form a new integer.
Return the maximum possible sum of the array after performing at most k operations.
Example 1:
Input: nums = [123,45], k = 1
Output: 366
Explanation:
- We choose nums[0] = 123 and rearrange its digits to form 321.
- The array becomes [321, 45]. Thus, the total sum is 321 + 45 = 366.
Example 2:
Input: nums = [102,90,14], k = 2
Output: 341
Explanation:
- We choose nums[0] = 102 and rearrange its digits to form 210.
- We choose nums[2] = 14 and rearrange its digits to form 41.
- The array becomes [210, 90, 41]. Thus, the total sum is 210 + 90 + 41 = 341.
Constraints:
1 <= n == nums.length <= 10^51 <= nums[i] <= 10^91 <= k <= n
Solution
Approach: Greedy by Gain
For each number, the best rearrangement puts its digits in descending order. Since nums[i] >= 1, the largest digit comes first and cannot be 0, so the result is a valid integer, and it is never smaller than the original. Call it t[i].
Because every gain t[i] - nums[i] is non-negative, using fewer operations than allowed never helps. Sort the indices by gain in descending order, take t for the first k of them and the original value for the rest, and sum.
Complexity: O(n log n) time and O(n) space (each number has at most 10 digits). The sum can exceed 32 bits, so use a 64-bit integer.
class Solution:
def maximizeSum(self, nums: List[int], k: int) -> int:
def f(x: int) -> int:
cnt = [0] * 10
while x:
x, v = divmod(x, 10)
cnt[v] += 1
y = 0
for i in range(9, -1, -1):
for _ in range(cnt[i]):
y = y * 10 + i
return y
n = len(nums)
t = [f(x) for x in nums]
ids = list(range(n))
ids.sort(key=lambda i: t[i] - nums[i], reverse=True)
return sum(t[ids[i]] if i < k else nums[ids[i]] for i in range(n))