diff --git a/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README.md b/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README.md index 41867015b1e1d..2f70357cedf60 100644 --- a/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README.md +++ b/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README.md @@ -63,6 +63,29 @@ ```python +class Solution: + def isPossible(self, target: List[int]) -> bool: + if len(target) == 1: + return target[0] == 1 + + summ = sum(target) + maxHeap = [-num for num in target] + heapq.heapify(maxHeap) + + while -maxHeap[0]> 1: + maxi = -heapq.heappop(maxHeap) + restSum = summ - maxi + # Only occurs if n == 2. + if restSum == 1: + return True + updated = maxi % restSum + # Updated == 0 (invalid) or didn't change. + if updated == 0 or updated == maxi: + return False + heapq.heappush(maxHeap, -updated) + summ = summ - maxi + updated + + return True ``` diff --git a/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README_EN.md b/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README_EN.md index 64cb1603eaf11..7839c8a3ff817 100644 --- a/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README_EN.md +++ b/solution/1300-1399/1354.Construct Target Array With Multiple Sums/README_EN.md @@ -58,6 +58,29 @@ ### **Python3** ```python +class Solution: + def isPossible(self, target: List[int]) -> bool: + if len(target) == 1: + return target[0] == 1 + + summ = sum(target) + maxHeap = [-num for num in target] + heapq.heapify(maxHeap) + + while -maxHeap[0]> 1: + maxi = -heapq.heappop(maxHeap) + restSum = summ - maxi + # Only occurs if n == 2. + if restSum == 1: + return True + updated = maxi % restSum + # Updated == 0 (invalid) or didn't change. + if updated == 0 or updated == maxi: + return False + heapq.heappush(maxHeap, -updated) + summ = summ - maxi + updated + + return True ``` diff --git a/solution/1300-1399/1354.Construct Target Array With Multiple Sums/Solution.py b/solution/1300-1399/1354.Construct Target Array With Multiple Sums/Solution.py new file mode 100644 index 0000000000000..ec3ecc99ba728 --- /dev/null +++ b/solution/1300-1399/1354.Construct Target Array With Multiple Sums/Solution.py @@ -0,0 +1,23 @@ +class Solution: + def isPossible(self, target: List[int]) -> bool: + if len(target) == 1: + return target[0] == 1 + + summ = sum(target) + maxHeap = [-num for num in target] + heapq.heapify(maxHeap) + + while -maxHeap[0]> 1: + maxi = -heapq.heappop(maxHeap) + restSum = summ - maxi + # Only occurs if n == 2. + if restSum == 1: + return True + updated = maxi % restSum + # Updated == 0 (invalid) or didn't change. + if updated == 0 or updated == maxi: + return False + heapq.heappush(maxHeap, -updated) + summ = summ - maxi + updated + + return True

AltStyle によって変換されたページ (->オリジナル) /