-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy path1354. Construct Target Array With Multiple Sums
More file actions
52 lines (38 loc) · 1.2 KB
/
1354. Construct Target Array With Multiple Sums
File metadata and controls
52 lines (38 loc) · 1.2 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
class Solution {
public boolean isPossible(int[] target) {
long sum =0;
int max=0;
for(int i=0;i<target.length;i++){
sum += target[i];
if(target[max]<target[i]){
max = i;
}
}
long diff = sum - target[max];
if(target[max] == 1 || diff == 1) return true;
if(diff>target[max] || diff == 0 || target[max]%diff==0) return false;
target[max] %= diff;
return isPossible(target);
}
}
//TC O(n*logN) SC O(N)
class Solution {
public boolean isPossible(int[] target) {
long sum =0;
PriorityQueue<Integer> pq=new PriorityQueue<Integer>((a,b)->b-a);
for(int i=0;i<target.length;i++){
sum += target[i];
pq.offer(target[i]);
}
while(pq.peek()!=1){
int value = pq.poll();
long diff = sum - value;
if(diff == 1) return true;
if(diff>value || diff == 0 || value%diff==0) return false;
value %= diff;
sum = diff + value;
pq.offer(value);
}
return true;
}
}