-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path105MinimumPairRemovaltoSortArrayI.cpp
More file actions
42 lines (36 loc) · 1.07 KB
/
Copy path105MinimumPairRemovaltoSortArrayI.cpp
File metadata and controls
42 lines (36 loc) · 1.07 KB
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
34
35
36
37
38
39
40
41
42
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int minimumPairRemoval(vector<int>& nums) {
int ops = 0;
auto nonDecreasing = [&](const vector<int>& a) {
for (int i = 1; i < (int)a.size(); ++i)
if (a[i] < a[i - 1]) return false;
return true;
};
while ((int)nums.size() > 1 && !nonDecreasing(nums)) {
long long bestSum = (long long)nums[0] + nums[1];
int idx = 0;
for (int i = 1; i < (int)nums.size() - 1; ++i) {
long long s = (long long)nums[i] + nums[i + 1];
if (s < bestSum) { // "<" keeps leftmost on ties automatically
bestSum = s;
idx = i;
}
}
nums[idx] = (int)bestSum;
nums.erase(nums.begin() + idx + 1);
++ops;
}
return ops;
}
};
int main(){
Solution obj;
vector<int> vecn = {5,2,3,1};
int result = obj.minimumPairRemoval(vecn);
cout<<result;
return 0;
}