- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 63 lines of C++ from the credited upstream file 3266.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 6 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {4 if (multiplier == 1)5 return nums;6 7 const int n = nums.size();8 const int maxNum = ranges::max(nums);9 vector<int> ans(n);10 using P = pair<int, int>; 11 priority_queue<P, vector<P>, greater<>> minHeap;12 13 for (int i = 0; i < n; ++i)14 minHeap.emplace(nums[i], i);15 16 17 18 19 20 while (k > 0 &&21 static_cast<long>(minHeap.top().first) * multiplier <= maxNum) {22 const auto [num, i] = minHeap.top();23 minHeap.pop();24 minHeap.emplace(num * multiplier, i);25 --k;26 }27 28 vector<pair<int, int>> sortedIndexedNums;29 while (!minHeap.empty())30 sortedIndexedNums.push_back(minHeap.top()), minHeap.pop();31 32 const int multipliesPerNum = k / n;33 const int remainingK = k % n;34 35 36 37 for (auto& [num, _] : sortedIndexedNums)38 num = (num * modPow(multiplier, multipliesPerNum)) % kMod;39 40 41 42 for (int i = 0; i < remainingK; ++i)43 sortedIndexedNums[i].first =44 (static_cast<long>(sortedIndexedNums[i].first) * multiplier % kMod);45 46 for (const auto& [num, i] : sortedIndexedNums)47 ans[i] = num;48 49 return ans;50 }51 52 private:53 static constexpr int kMod = 1'000'000'007;54 55 long modPow(long x, long n) {56 if (n == 0)57 return 1;58 if (n % 2 == 1)59 return x * modPow(x, n - 1) % kMod;60 return modPow(x * x % kMod, n / 2);61 }62};63