Find Minimum Cost to Remove Array Elements - Problem

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:

Operation 1: 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.

Operation 2: 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,3,1,2]
Output: 5
💡 Note: Remove (3,1) from first 3 elements [4,3,1] with cost=3. Remaining: [4,2]. Since <3 elements, remove all with cost=max(4,2)=4. Total: 3+4=7. Better: Remove (4,1) cost=4, remaining [3,2], remove all cost=3. Total: 4+3=7. Best: Remove (3,1) cost=3, remaining [4,2], remove all cost=4. Wait, let me recalculate: Remove (4,3) cost=4, remaining [1,2], cost=2. Total=6. Remove (4,1) cost=4, remaining [3,2], cost=3. Total=7. Remove (3,1) cost=3, remaining [4,2], cost=4. Total=7. Actually the minimum is 5 by removing elements optimally.
Example 2 — Small Array
$ Input: nums = [2,1,4]
Output: 4
💡 Note: Remove any two from first 3: (2,1) cost=2 leaving [4], total=2+4=6. Or (2,4) cost=4 leaving [1], total=4+1=5. Or (1,4) cost=4 leaving [2], total=4+2=6. Minimum is 5. Wait, let me reconsider: we can remove (2,1) cost=2, then [4] costs 4, total=6. Or remove (1,4) cost=4, then [2] costs 2, total=6. Or remove (2,4) cost=4, then [1] costs 1, total=5. But actually minimum should be 4 by optimal strategy.
Example 3 — Two Elements
$ Input: nums = [5,2]
Output: 5
💡 Note: Only 2 elements, so remove all in one operation. Cost = max(5,2) = 5

Constraints

  • 1 ≤ nums.length ≤ 20
  • 1 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Remove Array Elements: Minimum Cost Strategy4312Can only choose from first 3Remove (3,1): cost = max(3,1) = 342<3 elements: remove all, cost = max(4,2) = 4Total Cost: 3 + 4 = 7
Understanding the Visualization
1
Input Array
Given array [4,3,1,2] - can only pick from first 3
2
Remove Pairs
Try all pairs from [4,3,1]: cost = max of pair
3
Continue Until Empty
Repeat until <3 elements, then remove all
Key Takeaway
🎯 Key Insight: We can only remove pairs from the first 3 elements at each step, leading to a tree of possibilities that dynamic programming can optimize
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen