How to optimally divide an array into two subarrays so that sum of elements in both are same, otherwise give an error?

前端 未结 22 970
一生所求
一生所求 2020-12-02 11:20

How to optimally divide an array into two subarrays so that sum of elements in both subarrays is same, otherwise give an error?

Example 1

Given the array

22条回答
  •  独厮守ぢ
    2020-12-02 12:06

    A non optimal solution in python,

    from itertools import permutations
    
    def get_splitted_array(a):
      for perm in permutations(a):
        l1 = len(perm)
        for i in range(1, l1):
          if sum(perm[0:i]) == sum(perm[i:l1]):
            return perm[0:i], perm[i:l1]
    
    >>> a = [6,1,3,8]
    >>> get_splitted_array(a)
    ((6, 3), (1, 8))
    >>> a = [5,9,20,1,5]
    >>> 
    >>> get_splitted_array(a)
    ((5, 9, 1, 5), (20,))
    >>> 
    
    

提交回复
热议问题