[LeetCode] Find Minimum Cost to Remove Array Elements

3469. 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.

c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
array<int,3> order(int a, int b, int c) {
if(a > b) swap(a, b);
if(b > c) swap(b, c);
if(a > b) swap(a, b);
return {a,b,c};
}
public:
int minCost(vector<int>& nums) {
map<int,int> dp{{nums[0],0}};
int base = 0;
if(nums.size() % 2 == 0) {
base = nums.back(); nums.pop_back();
}
for(int i = 1; i < nums.size(); i += 2) {
map<int,int> dpp;
auto push = [&](int carry, int val) {
if(!dpp.count(carry)) dpp[carry] = val;
else dpp[carry] = min(dpp[carry], val);
};
int x = nums[i], y = nums[i+1];
for(auto& [carry, val] : dp) {
auto [a,b,c] = order(x,y,carry);
push(a, val + c);
push(c, val + b);
}
swap(dp,dpp);
}
int res = INT_MAX;
for(auto& [carry, val] : dp) res = min(res, max(carry,base) + val);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/03/02/PS/LeetCode/find-minimum-cost-to-remove-array-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.

Related Issues not found

Please contact @SongHayoung to initialize the comment