Minimum Sum After Divisible Sum Deletions Problem
Description
LeetCode Problem 3654.
You are given an integer array nums and an integer k.
You may repeatedly choose any contiguous subarray of nums whose sum is divisible by k and delete it; after each deletion, the remaining elements close the gap.
Return the minimum possible sum of nums after performing any number of such deletions.
Example 1:
Input: nums = [1,1,1], k = 2
Output: 1
Explanation:
- Delete the subarray nums[0..1] = [1, 1], whose sum is 2 (divisible by 2), leaving [1].
- The remaining sum is 1.
Example 2:
Input: nums = [3,1,4,1,5], k = 3
Output: 5
Explanation:
- First, delete nums[1..3] = [1, 4, 1], whose sum is 6 (divisible by 3), leaving [3, 5].
- Then, delete nums[0..0] = [3], whose sum is 3 (divisible by 3), leaving [5].
- The remaining sum is 5.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^61 <= k <= 10^5
Solution
Approach: DP over Prefix Sums
Let dp[i] be the smallest sum that can remain from the first i elements. Either element i stays, giving dp[i - 1] + nums[i - 1], or it is removed as the end of a deleted block that starts after some j < i. That block can be deleted when its sum is divisible by k, which means the prefix sums at j and i have the same remainder modulo k. In that case dp[i] can be as small as dp[j].
So, while scanning the array, keep best[r]: the smallest dp[j] over all prefixes j whose prefix sum has remainder r. At each step update the prefix remainder s, then set dp = min(dp + x, best[s]) and best[s] = min(best[s], dp). Start with best[0] = 0 (the empty prefix) and everything else infinite. The answer is the final dp.
Complexity: O(n + k) time and O(k) extra space.
from math import inf
class Solution:
def minArraySum(self, nums: List[int], k: int) -> int:
best = [inf] * k # best[r]: smallest dp[j] over prefixes j with prefix sum % k == r
best[0] = 0
dp = 0 # minimum remaining sum of the current prefix
s = 0
for x in nums:
s = (s + x) % k
dp = min(dp + x, best[s])
best[s] = min(best[s], dp)
return dp