Problem · Array

Find Minimum Cost to Remove Array Elements

Learn this problem
MediumMathWorks logoMathWorksFULLTIMEONSITE INTERVIEW

Problem 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[]) → int

Examples

Example 1

nums = [3,1,4,2]return = 6

Remove 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 = 4

Remove 2 and 3 for a cost of 3, then remove the remaining 1 for a cost of 1.

Constraints

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 10^6

More MathWorks problems

drafts saved locally
public int minCost(int[] nums) {
  // Write your code here.
}
nums[3,1,4,2]
expected6
checking account