From f68ee5e7ec6984dfbac0f8916df087bba4b4241e Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Mon, 11 Nov 2024 23:40:15 +0530 Subject: [PATCH] Create 2601. Prime Subtraction Operation --- 2601. Prime Subtraction Operation | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 2601. Prime Subtraction Operation 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; + } +};