Check if array sum can be made K by three operations on it in Python


Suppose we have a list of numbers called nums and also a positive value K. We can perform any of these three operations on nums −

  • Make one number negative,
  • Add index (start from index 1) of the number to the number itself
  • Subtract index of the number from the number itself.

Finally, we have to check whether the given array can be transformed as the sum of the array becomes k, by performing these operations only once on each element.

So, if the input is like nums = [1,2,3,7] k = 8, then the output will be True as we can subtract index of 2 and 3 from 2 and 3 to make array like [1, 0, 0, 7], so now the sum is 8 = k.

To solve this, we will follow these steps −

  • size := 100
  • Define a function is_ok() . This will take i, total, k, nums, table
  • n := size of nums
  • if total <= 0, then
    • return False
  • if i >= n, then
    • if total is same as k, then
      • return True
  • return False
  • if table[i, total] is not -1, then
    • return table[i, total]
  • table[i, total] := 1 when (is_ok(i+1, total - 2 * nums[i], k, nums, table) is non-zero or is_ok(i+1, total, k, nums, table) is non-zero), otherwise 0
  • table[i, total] := 1 when (is_ok(i+1, total -(i+1) , k, nums, table) or table[i, total]), otherwise 0
  • table[i, total] := 1 when (is_ok(i+1, total + i + 1, k, nums, table) or table[i, total]), otherwise 0
  • return table[i, total]
  • From the main method do the following −
  • total := sum of all elements in nums
  • table := an array of length same as size and fill with -1
  • for i in range 0 to size, do
    • table[i] := an array of length same as size and fill with -1
  • return is_ok(0, total, k, nums, table)

Let us see the following implementation to get better understanding −

Example

 Live Demo

size = 100
def is_ok(i, total, k, nums, table):
   n = len(nums)
   if total <= 0:
      return False
   if i >= n:
      if total == k:
         return True
      return False
   if table[i][total] != -1:
      return table[i][total]
   table[i][total] = is_ok(i+1, total - 2 * nums[i], k, nums, table) or is_ok(i+1, total, k, nums, table)
   table[i][total] = is_ok(i+1, total - (i+1), k, nums, table) or table[i][total] table[i][total] = is_ok(i+1, total + i + 1, k, nums, table) or table[i][total]
   return table[i][total]
def solve(nums, k):
   total = sum(nums)
   table = [-1]*size
   for i in range(size):
      table[i] = [-1]*size
   return is_ok(0, total, k, nums, table)
nums = [1,2,3,7]
k = 8
print(solve(nums, k))

Input

[1,2,3,7], 8

Output

True

Updated on: 30-Dec-2020

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements