- Related Questions & Answers
- Program to check robot can reach target position or not in Python
- Program to check we can spell out the target by a list of words or not in Python
- Program to check we can reach leftmost or rightmost position or not in Python
- Program to check we can reach end of list by starting from k in Python
- Program to check we can cross river by stones or not in Python
- Program to check robot can reach target by keep moving on visited spots in Python
- Program to check whether we can reach last position from index 0 in Python
- Program to check person can reach top-left or bottomright cell avoiding fire or not in Python
- Program to check whether we can split list into consecutive increasing sublists or not in Python
- Program to check whether we can take all courses or not in Python
- Program to check whether we can unlock all rooms or not in python
- Program to check we can form array from pieces or not in Python
- Python program to check whether a list is empty or not?
- Program to find minimum steps to reach target position by a chess knight in Python
- Program to check we can find four elements whose sum is same as k or not in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a list of numbers called target. Now let us consider a list X with the same length as given list and X is filled with 1s. We can perform the following operation as many times as we want: Take any index i in X and set X[i] to the current sum of X. Finally check whether X can be turned into target or not.

So, if the input is like target = [5, 9, 3], then the output will be True as initially X = [1, 1, 1], then update it with total sum 3, array will be [1, 1, 3], current sum is 5, update it [5, 1, 3], current sum 9, so list will be [5, 9, 3], and it is the target.

To solve this, we will follow these steps:

- if nums has only one element, then
- return true when nums has 1

- q := a queue with negative value of all numbers nums
- make q as heap
- s := sum of all numbers in nums
- ok := True
- while ok is True, do
- x := delete element from heap and negate it
- d := s - x
- x2 := x mod d if d > 1 otherwise 1
- s := s + x2 - x
- ok := x is not same as x2
- x := x2
- insert -x into heap q

- return true when all elements in q is -1

Let us see the following implementation to get better understanding:

class Solution: def solve(self, nums): if len(nums) == 1: return nums == [1] from heapq import heapify, heappop, heappush q = [-x for x in nums] heapify(q) s = sum(nums) ok = True while ok: x = -heappop(q) d = s - x x2 = x % d if d > 1 else 1 s += x2 - x ok = x != x2 x = x2 heappush(q, -x) return all(x == -1 for x in q) ob = Solution() target = [5, 9, 3] print(ob.solve(target))

[5, 9, 3]

True

Advertisements