diff --git a/2601. Prime Subtraction Operation b/2601. Prime Subtraction Operation new file mode 100644 index 0000000..76708ab --- /dev/null +++ b/2601. Prime Subtraction Operation @@ -0,0 +1,36 @@ +const int N = 1000; +vector lp(N + 1); +vector pr; + +void linearSieve() { + for (int i = 2; i <= N; ++i) { + if (lp[i] == 0) { + lp[i] = i; + pr.push_back(i); + } + for (int j = 0; i * pr[j] <= N; ++j) { + lp[i * pr[j]] = pr[j]; + if (pr[j] == lp[i]) { + break; + } + } + } +} + +class Solution { +public: + bool primeSubOperation(vector& nums) { + int n = nums.size(); + if (n == 1) return true; + linearSieve(); + for (int i = n - 2; i >= 0; --i) { + if (nums[i] >= nums[i + 1]) { + int target = nums[i] - nums[i + 1] + 1; + auto it = lower_bound(pr.begin(), pr.end(), target); + if (it == pr.end() || *it >= nums[i]) return false; + nums[i] -= *it; + } + } + return true; + } +};