Check if an array of 1s and 2s can be divided into 2 parts with equal sum in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array nums which only stores 1 and 2 in it. We have to check whether the array can be divided into two different parts such that sum of elements in each part is same.

So, if the input is like nums = [1, 1, 2, 2, 2], then the output will be True as we can divide this array like [1, 1, 2] and [2, 2] the sum of each part is 4.

To solve this, we will follow these steps −

  • total := 0, one_count := 0
  • total := sum of all elements of nums
  • one_count := count of 1s in nums
  • if total is even, then
    • return False
  • if integer part of (total / 2) is even, then
    • return True
  • if one_count > 0, then
    • return True
  • otherwise,
    • return False

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(nums):
   total = 0
   one_count = 0
   total = sum(nums)
   one_count = nums.count(1)
   if total % 2:
      return False
   if (total // 2) % 2 == 0:
      return True
   if one_count > 0:
      return True
   else:
      return False
nums = [1, 1, 2, 2, 2]
print(solve(nums))

Input

[1, 1, 2, 2, 2]

Output

True
raja
Published on 30-Dec-2020 12:46:58
Advertisements