Find Minimum Cost to Remove Array Elements Problem
#3469
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3469.
You are given an integer array nums. Your task is to remove all elements from the array by performing one of the following operations at each step until nums is empty:
- Choose any two elements from the first three elements of
numsand remove them. The cost of this operation is the maximum of the two elements removed. - If fewer than three elements remain in
nums, remove all the remaining elements in a single operation. The cost of this operation is the maximum of the remaining elements.
Return the minimum cost required to remove all the elements.
Example 1:
Input: nums = [6,2,8,4]
Output: 12
Explanation:
Initially, nums = [6, 2, 8, 4].
- In the first operation, remove nums[0] = 6 and nums[2] = 8 with a cost of max(6, 8) = 8. Now, nums = [2, 4].
- In the second operation, remove the remaining elements with a cost of max(2, 4) = 4.
The cost to remove all elements is 8 + 4 = 12. This is the minimum cost to remove all elements in nums. Hence, the output is 12.
Example 2:
Input: nums = [2,1,3,3]
Output: 5
Explanation:
Initially, nums = [2, 1, 3, 3].
- In the first operation, remove nums[0] = 2 and nums[1] = 1 with a cost of max(2, 1) = 2. Now, nums = [3, 3].
- In the second operation remove the remaining elements with a cost of max(3, 3) = 3.
The cost to remove all elements is 2 + 3 = 5. This is the minimum cost to remove all elements in nums. Hence, the output is 5.
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 10^6
Solution
Approach: Dynamic Programming
Only the first three elements matter at any time. After some operations the array looks like one leftover element nums[j] followed by the untouched suffix nums[i..], so the state (i, j) is enough.
Let dfs(i, j) be the minimum cost to remove everything from that state; the answer is dfs(1, 0). The first three elements are nums[j], nums[i] and nums[i + 1]:
- if
i >= n, onlynums[j]is left: its value; - if
i == n - 1, two elements are left:max(nums[j], nums[i]); - otherwise remove one of the three pairs and keep the third element as the new leftover:
- remove
iandi + 1, keepj:max(nums[i], nums[i+1]) + dfs(i + 2, j); - remove
jandi, keepi + 1:max(nums[j], nums[i]) + dfs(i + 2, i + 1); - remove
jandi + 1, keepi:max(nums[j], nums[i+1]) + dfs(i + 2, i).
- remove
Take the minimum and memoize.
Complexity: O(n^2) time and space.
from functools import lru_cache
class Solution:
def minCost(self, nums: List[int]) -> int:
n = len(nums)
@lru_cache(None)
def dfs(i: int, j: int) -> int:
if i >= n:
return nums[j]
if i == n - 1:
return max(nums[j], nums[i])
a, b = nums[i], nums[i + 1]
return min(
max(a, b) + dfs(i + 2, j),
max(nums[j], a) + dfs(i + 2, i + 1),
max(nums[j], b) + dfs(i + 2, i),
)
return dfs(1, 0)