Program to check we can update a list index by its current sum to reach target or not in python

PythonServer Side ProgrammingProgramming

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:

Example

Live Demo

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))

Input

[5, 9, 3]

Output

True
raja
Published on 26-Nov-2020 07:03:43
Advertisements