1827. Minimum Operations to Make the Array Increasing
贪心。在保持递增的同时,使得数字尽可能小。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intminOperations(vector<int>& nums){ // greedy // time: O(N) int last = 0; int ans = 0; for (int i : nums) { if (i > last) { last = i; } else { ans += last + 1 - i; ++last; } } return ans; } };
classSolution { public: vector<int> getMaximumXor(vector<int>& nums, int maximumBit){ int currentXOR = accumulate(nums.begin(), nums.end(), 0, [](int a, int b) -> int { return a ^ b; }); auto findMax = [&](constint a) -> int { // argmax a ^ k int k = 0; for (int i = maximumBit - 1; i >= 0; --i) { if (!(a & (1 << i))) { k |= (1 << i); } } return k; }; vector<int> ans; ans.reserve(nums.size()); for (auto it = nums.rbegin(); it != nums.rend(); ++it) { constint x = *it; ans.push_back(findMax(currentXOR)); currentXOR ^= x; } return ans; } };