Minimum Cost to Delete Array Problem
Description
LeetCode Problem 4123.
You are given an integer array nums.
In one operation, choose any subarray of the current array with length at least two and delete it. The cost of this operation is the sum of the first and last elements of the chosen subarray.
After each operation, the remaining elements are concatenated in their original order.
Return the minimum total cost required to delete the entire array.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [2,-7,3,-5]
Output: -7
Explanation:
- Delete [-7, 3] with cost -7 + 3 = -4. The array becomes [2, -5].
- Delete [2, -5] with cost 2 + (-5) = -3.
- The total cost is -4 + (-3) = -7.
Example 2:
Input: nums = [4,0,-5,2]
Output: 1
Explanation:
- Delete [0, -5] with cost 0 + (-5) = -5. The array becomes [4, 2].
- Delete [4, 2] with cost 4 + 2 = 6.
- The total cost is -5 + 6 = 1.
Example 3:
Input: nums = [7,-8,1]
Output: 8
Explanation:
- To delete the entire array, all three elements must be deleted in one operation. Deleting only two elements would leave one element, which cannot be deleted.
- Deleting [7, -8, 1] costs 7 + 1 = 8.
Constraints:
2 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Greedy on Sorted Middle Elements
Every operation costs the sum of its two end elements, and the elements in between are free. So the total cost is the sum of the elements that serve as an end of some operation.
The first and last element of the array can never be inside another operation's range, so they are always ends. Beyond those two, any even number of the middle elements can also be made ends: delete them in pairs (the elements between a pair are removed for free), and finish with one operation on the first and last element. The number of ends is always even, because each operation has exactly two of them. An odd number of extra ends is not possible.
So the answer is nums[0] + nums[n - 1] plus the smallest possible sum of an even-sized subset of the middle elements. Sort the middle, then take consecutive pairs (mid[0], mid[1]), (mid[2], mid[3]), ... as long as a pair's sum is negative. Pair sums only grow along the sorted order, so we can stop at the first non-negative one.
Complexity: O(n log n) time and O(n) extra space.
class Solution:
def minCost(self, nums: List[int]) -> int:
# The two ends must be endpoints of operations; any even number of the
# middle elements can be made endpoints of extra operations as well.
mid = sorted(nums[1:-1])
ans = nums[0] + nums[-1]
for i in range(0, len(mid) - 1, 2):
pair = mid[i] + mid[i + 1]
if pair >= 0:
break
ans += pair
return ans