class Solution{public: int countOperations(int num1, int num2) { int ans = 0; while (num1 != 0 && num2 != 0) { if (num1 < num2) { swap(num1, num2); } ans++; num1 -= num2; } return ans; }};
2. Minimum Operations to Make the Array Alternating
So basically we need to decide the first two numbers only.
For each number, we may only consider the top-2 frequent numbers within that group.
Or we may consider a totally different number (in case all numbers are same).
● ● ●c++
class Solution{public: vector<int> common(vector<int> &nums) { unordered_map<int, int> cnt; for (auto &x : nums) { cnt[x]++; } vector<int> ans; for (auto &pair : cnt) { if (ans.size() < 2) { ans.push_back(pair.first); continue; } if (pair.second > cnt[ans[0]]) { ans[1] = ans[0]; ans[0] = pair.first; } else if (pair.second > cnt[ans[1]]) { ans[1] = pair.first; } } ans.push_back(0); return ans; } int minimumOperations(vector<int>& nums) { int n = nums.size(); vector<int> a, b; for (int i = 0; i < n; i++) { if (i % 2 == 0) { a.push_back(nums[i]); } else { b.push_back(nums[i]); } } vector<int> ta = common(a), tb = common(b); int ans = INT_MAX; for (auto &pa : ta) { for (auto &pb : tb) { if (pa == pb) { continue; } int tmp = 0; for (auto &x : a) { if (x != pa) { tmp++; } } for (auto &x : b) { if (x != pb) { tmp++; } } ans = min(ans, tmp); } } return ans; }};
3. Removing Minimum Number of Magic Beans
Let's say the final equal number is x.
For numbers which are lower than x, we should take all beans from relative bags.
For numbers which are higher or equal than x, reduce the number to x.
Sort and linear-scan.
● ● ●c++
class Solution{public: long long minimumRemoval(vector<int>& beans) { int n = beans.size(); sort(beans.begin(), beans.end()); long long total = 0; for (auto &x : beans) { total += x; } long long a = 0, ans = total; for (long long i = 0; i < n; i++) { long long tmp = a + (total - a - (n - i) * beans[i]); ans = min(ans, tmp); } return ans; }};