-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathisPossible.cpp
More file actions
52 lines (50 loc) · 1.6 KB
/
isPossible.cpp
File metadata and controls
52 lines (50 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// https://leetcode.cn/problems/construct-target-array-with-multiple-sums/solution/duo-ci-qiu-he-gou-zao-mu-biao-shu-zu-by-leetcode-s/
class Solution {
public:
bool isPossible(vector<int>& target) {
if (target.size() == 1) return target[0] == 1;
priority_queue<int> pq;
long long total = 0;
for (int e: target) {
pq.push(e);
total += e;
}
while (!pq.empty()) {
int x = pq.top();
pq.pop();
if (x == 1) break;
if (x + x - total < 1)
return false;
long long left = total - x, y = pq.top(), k;
if (y == 1) k = (x - y + left - 1) / left;
else k = (x - y) / left + 1;
x -= k * left;
if (x <= 0) return false;
total -= k * left;
pq.push(x);
}
return true;
}
};
// https://leetcode.cn/problems/construct-target-array-with-multiple-sums/solution/cni-tui-you-xian-dui-lie-by-monologue-s-dcso/
class Solution {
public:
bool isPossible(vector<int>& target) {
long long sum = 0;
priority_queue<long long> q;
for(int ev: target){
sum += ev;
q.push(ev);
}
while(q.top() != 1){
long long curMax = q.top(); q.pop();
long long otherSum = sum - curMax;
if(curMax - otherSum < 1 || otherSum == 0) return false;
long long temp = curMax % otherSum;
if(temp == 0) temp = otherSum;
q.push(temp);
sum = sum - curMax + temp;
}
return true;
}
};