leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
2856.cpp (1194B)
0 class Solution { 1 public: 2 int minLengthAfterRemovals(const vector<int> &nums) const { 3 priority_queue<int> pq; 4 5 int count = 1; 6 for (int i = 1; i < nums.size(); i++) { 7 if (nums[i] != nums[i - 1]) { 8 pq.push(count); 9 count = 1; 10 } else 11 count++; 12 } 13 pq.push(count); 14 15 while (pq.size() > 1) { 16 const int first = pq.top(); 17 pq.pop(); 18 const int second = pq.top(); 19 pq.pop(); 20 if (first > 1) pq.push(first - 1); 21 if (second > 1) pq.push(second - 1); 22 } 23 24 return pq.size() ? pq.top() : 0; 25 } 26 }; 27 28 // Not sure why this works... 29 class Solution { 30 public: 31 int minLengthAfterRemovals(const vector<int> &nums) const { 32 const int n = nums.size(); 33 int count = 1, maxi = 0; 34 for (int i = 1; i < n; i++) { 35 if (nums[i] != nums[i - 1]) { 36 maxi = max(maxi, count); 37 count = 1; 38 } else 39 count++; 40 } 41 maxi = max(maxi, count); 42 43 if (maxi <= n / 2) return n % 2; 44 return 2 * maxi - n; 45 } 46 };