Skip to content

Commit

Permalink
Create 2601. Prime Subtraction Operation (#632)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chayandas07 authored Nov 11, 2024
2 parents 780e8aa + f68ee5e commit 771a47b
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions 2601. Prime Subtraction Operation
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const int N = 1000;
vector<int> lp(N + 1);
vector<int> 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<int>& 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;
}
};

0 comments on commit 771a47b

Please sign in to comment.