classSolution { public: intminAbsoluteDifference(vector<int>& nums, int x){ set<int> cnt; int res = INT_MAX; int n = nums.size(); for (int i = 0, j = 0; i < n; i++) { if (i - j >= x) { cnt.emplace(nums[j++]); auto it = cnt.lower_bound(nums[i]); if (it != cnt.end()) { res = min(res, abs(*it - nums[i])); } if (it != cnt.begin()) { it--; res = min(res, abs(*it - nums[i])); } } } return res; } };
7023. 操作使得分最大
给你一个长度为 n 的正整数数组 nums 和一个整数 k 。
一开始,你的分数为 1 。你可以进行以下操作至多 k 次,目标是使你的分数最大:
选择一个之前没有选过的 非空 子数组 nums[l, ..., r] 。
从 nums[l, ..., r] 里面选择一个 质数分数 最高的元素 x 。如果多个元素质数分数相同且最高,选择下标最小的一个。
将你的分数乘以 x 。
nums[l, ..., r] 表示 nums 中起始下标为 l ,结束下标为 r 的子数组,两个端点都包含。
classSolution { public: longlongfastpow(longlong x, longlong n, longlong mod){ longlong res = 1; longlong cur = x; for (int i = n; i != 0; i >>= 1) { if (i & 1) { res = (res * cur) % mod; } cur = (cur * cur) % mod; } return res; }
intmaximumScore(vector<int>& nums, int k){ int maxVal = *max_element(nums.begin(), nums.end()); vector<int> arr; vector<int> primer; vector<bool> visit(maxVal + 1, false); for (int i = 2; i <= maxVal; i++) { if (!visit[i]) { primer.emplace_back(i); for (int j = i; j <= maxVal; j += i) { visit[j] = true; } } } for (int i = 0; i < nums.size(); i++) { int x = nums[i], tot = 0; for (auto v : primer) { if (x < v) break; if (x % v == 0) { tot++; while (x != 0 && (x % v) == 0) { x /= v; } } } arr.emplace_back(tot); } int n = nums.size(); vector<int> left(n), right(n); stack<int> st1; for (int i = 0; i < n; i++) { while (!st1.empty() && arr[st1.top()] < arr[i]) { st1.pop(); } left[i] = st1.empty() ? (i + 1) : (i - st1.top()); st1.emplace(i); } stack<int> st2; for (int i = n - 1; i >= 0; i--) { while (!st2.empty() && arr[st2.top()] <= arr[i]) { st2.pop(); } right[i] = st2.empty() ? (n - i) : (st2.top() - i); st2.emplace(i); } vector<pair<int, int>> cnt; for (int i = 0; i < n; i++) { cnt.emplace_back(nums[i], right[i] * left[i]); } sort(cnt.begin(), cnt.end(), [&](pair<int, int> &a, pair<int, int> &b) { return a.first > b.first; }); longlong ans = 1; longlong mod = 1e9 + 7; for (int i = 0, j = k; i < n && j > 0; i++) { auto [val, freq] = cnt[i]; int tot = min(freq, j); ans = (ans * fastpow(val, tot, mod)) % mod; j -= freq; } return ans; } };