Program to find ways to make a fair array in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array called nums. We can select exactly one index and remove the element from that index. (The index of the elements may change after the removal). We can say an array is fair when the sum of the odd-indexed values equals the sum of the even-indexed values. We have to find the number of indices that we could select such that after the removal, nums is fair.

So, if the input is like nums = [5,3,7,2], then the output will be

  • Remove from index 0, array is [3,7,2], even position sum: 3+2 = 5, odd position sum 7 (Not fair)

  • Remove from index 1, array is [5,7,2], even position sum: 5+2 = 7, odd position sum 7 (fair)

  • Remove from index 2, array is [5,3,2], even position sum: 5+2 = 7, odd position sum 3 (Not fair)

  • Remove from index 3, array is [5,3,7], even position sum: 5+7 = 12, odd position sum 3 (Not fair)

To solve this, we will follow these steps −

  • res := 0, sm1 := 0, sm2 := 0
  • for i in range 1 to size of nums - 1, do
    • if i is even, then
      • sm1 := sm1 + nums[i]
    • otherwise,
      • sm2 := sm2 + nums[i]
  • if sm1 is same as sm2, then
    • res := res + 1
  • for i in range 1 to size of nums - 1, do
    • if i is odd, then
      • sm1 := sm1 - nums[i] + nums[i-1]
    • otherwise,
      • sm2 := sm2 - nums[i] + nums[i-1]
    • if sm1 is same as sm2, then
      • res := res + 1
  • return res

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   res, sm1, sm2 = 0, 0, 0
   for i in range(1, len(nums)):
      if i%2 == 1:
         sm1 += nums[i]
      else:
         sm2 += nums[i]
   if sm1 == sm2:
      res += 1

   for i in range(1, len(nums)):
      if i % 2 == 1:
         sm1 = sm1 - nums[i] + nums[i-1]
      else:
         sm2 = sm2 - nums[i] + nums[i-1]
      if sm1 == sm2:
         res += 1

   return res

nums = [5,3,7,2]
print(solve(nums))

Input

[5,3,7,2]

Output

1
raja
Published on 05-Oct-2021 12:45:38
Advertisements