Problem · Array
Find Minimum Cost to Remove Array Elements
Learn this problemProblem statement
You are given an integer array nums. Remove all elements by repeatedly applying these rules:
- When at least three elements remain, choose any two of the first three elements and remove them. The operation costs the maximum of the two removed values.
- When fewer than three elements remain, remove all remaining elements in one operation. That operation costs the maximum remaining value.
Return the minimum total cost required to remove every element.
Function
minCost(nums: int[]) → intExamples
Example 1
nums = [3,1,4,2]return = 6Remove 3 and 4 from the first three elements for a cost of 4. The remaining array is [1,2]; removing both costs 2. The minimum total is 6.
Example 2
nums = [1,2,3]return = 4Remove 2 and 3 for a cost of 3, then remove the remaining 1 for a cost of 1.
Constraints
1 <= nums.length <= 10001 <= nums[i] <= 10^6