Find Minimum Cost to Remove Array Elements

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 nums and 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
Inputnums = [6,2,8,4]
Output12
Removing 6 and 8 first costs 8, then removing the remaining 2 and 4 costs 4, for a minimum total cost of 12.
Example 2
Inputnums = [2,1,3,3]
Output5
Removing 2 and 1 first costs 2, then removing the remaining 3 and 3 costs 3, for a minimum total cost of 5.

Constraints

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

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate