Skip to content

Commit cce5b39

Browse files
committed
Added solution for 1354.
1 parent dd85b2c commit cce5b39

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

solution/1300-1399/1354.Construct Target Array With Multiple Sums/README.md

+23
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,29 @@
6363
<!-- 这里可写当前语言的特殊实现逻辑 -->
6464

6565
```python
66+
class Solution:
67+
def isPossible(self, target: List[int]) -> bool:
68+
if len(target) == 1:
69+
return target[0] == 1
70+
71+
summ = sum(target)
72+
maxHeap = [-num for num in target]
73+
heapq.heapify(maxHeap)
74+
75+
while -maxHeap[0] > 1:
76+
maxi = -heapq.heappop(maxHeap)
77+
restSum = summ - maxi
78+
# Only occurs if n == 2.
79+
if restSum == 1:
80+
return True
81+
updated = maxi % restSum
82+
# Updated == 0 (invalid) or didn't change.
83+
if updated == 0 or updated == maxi:
84+
return False
85+
heapq.heappush(maxHeap, -updated)
86+
summ = summ - maxi + updated
87+
88+
return True
6689

6790
```
6891

solution/1300-1399/1354.Construct Target Array With Multiple Sums/README_EN.md

+23
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,29 @@
5858
### **Python3**
5959

6060
```python
61+
class Solution:
62+
def isPossible(self, target: List[int]) -> bool:
63+
if len(target) == 1:
64+
return target[0] == 1
65+
66+
summ = sum(target)
67+
maxHeap = [-num for num in target]
68+
heapq.heapify(maxHeap)
69+
70+
while -maxHeap[0] > 1:
71+
maxi = -heapq.heappop(maxHeap)
72+
restSum = summ - maxi
73+
# Only occurs if n == 2.
74+
if restSum == 1:
75+
return True
76+
updated = maxi % restSum
77+
# Updated == 0 (invalid) or didn't change.
78+
if updated == 0 or updated == maxi:
79+
return False
80+
heapq.heappush(maxHeap, -updated)
81+
summ = summ - maxi + updated
82+
83+
return True
6184

6285
```
6386

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution:
2+
def isPossible(self, target: List[int]) -> bool:
3+
if len(target) == 1:
4+
return target[0] == 1
5+
6+
summ = sum(target)
7+
maxHeap = [-num for num in target]
8+
heapq.heapify(maxHeap)
9+
10+
while -maxHeap[0] > 1:
11+
maxi = -heapq.heappop(maxHeap)
12+
restSum = summ - maxi
13+
# Only occurs if n == 2.
14+
if restSum == 1:
15+
return True
16+
updated = maxi % restSum
17+
# Updated == 0 (invalid) or didn't change.
18+
if updated == 0 or updated == maxi:
19+
return False
20+
heapq.heappush(maxHeap, -updated)
21+
summ = summ - maxi + updated
22+
23+
return True

0 commit comments

Comments
 (0)