Skip to content

Commit 28df685

Browse files
authored
Create construct-target-array-with-multiple-sums.cpp
1 parent bf8fb37 commit 28df685

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Time: O(log(max(t)) * logn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
bool isPossible(vector<int>& target) {
7+
// (1) x + remain = y
8+
// (2) y + remain = total
9+
// (1) - (2) => x - y = y - total
10+
// => x = 2*y - total
11+
auto total = accumulate(begin(target), end(target), 0ll);
12+
priority_queue<int> max_heap(target.cbegin(), target.cend());
13+
while (total != target.size()) {
14+
const auto y = max_heap.top(); max_heap.pop();
15+
const auto& remain = total - y;
16+
auto x = y - remain;
17+
if (x <= 0) {
18+
return false;
19+
}
20+
if (x > remain) { // for case [1, 1000000000]
21+
x = x % remain + remain;
22+
}
23+
max_heap.emplace(x);
24+
total = x + remain;
25+
}
26+
return true;
27+
}
28+
};

0 commit comments

Comments
 (0)