- 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
- 64 lines of C++ from the credited upstream file minimum-stability-factor-of-array.cpp.
- The implementation visibly relies on sequence storage.
- 4 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.
123 45class Solution {6public:7 int minStable(vector<int>& nums, int maxC) {8 const auto& binary_search_right = [&](int left, int right, const auto& check) {9 while (left <= right) {10 const int mid = left + (right - left) / 2;11 if (!check(mid)) {12 right = mid - 1;13 } else {14 left = mid + 1;15 }16 }17 return right;18 };19 20 SparseTable rmq(nums, gcd<int, int>);21 const auto& check = [&](int l) {22 int cnt = 0;23 for (int i = 0; i + l - 1 < size(nums);) {24 if (rmq.query(i, i + l - 1) >= 2) {25 ++cnt;26 i += l;27 } else {28 ++i;29 }30 }31 return cnt > maxC;32 };33 34 return binary_search_right(1, size(nums), check);35 }36 37private:38 39 class SparseTable {40 public:41 SparseTable(const vector<int>& arr, function<int (int, int)> fn)42 : fn(fn) { 43 const int n = size(arr);44 const int k = __lg(n);45 st.assign(k + 1, vector<int64_t>(n));46 st[0].assign(cbegin(arr), cend(arr));47 for (int i = 1; i <= k; ++i) {48 for (int j = 0; j + (1 << i) <= n; ++j) {49 st[i][j] = fn(st[i - 1][j], st[i - 1][j + (1 << (i - 1))]);50 }51 }52 }53 54 int64_t query(int L, int R) const {55 const int i = __lg(R - L + 1);56 return fn(st[i][L], st[i][R - (1 << i) + 1]); 57 }58 59 private:60 vector<vector<int64_t>> st;61 const function<int (int, int)>& fn;62 };63};64