Home > front end >  Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum
Split the given array into K sub-arrays such that maximum sum of all sub arrays is minimum

Time:01-25

For a given array I am trying to calculate the Min-Max subarrays. Here is my code for calculating. I have derived the subproblem and tried to do it using dynamic programming (Using only recursion, not memoization or tabulation). Please let me know what is wrong because it is showing list cannot be iterpreted as an integer.

def Opt(i,j):
    if (j==1):
        return sum(i)
    else:
        val = [max(Opt(l,j-1), sum(i[l:j])) for l in range(1,i,1)]
        return min(val)



# Driver Code
if __name__ == '__main__':
    S = [5, 7, 4, 2, 1, 6]
    k = 3
    ans = Opt(S,k)
    print(ans)
'''

CodePudding user response:

range(1,i,1) is the problem, specifically i - you're passing in the full list and range() expects an integer. Do you want the length of the list, len(i)?

CodePudding user response:

I have solved a similar answer, but I found the following solution for the exact question. So I'm directly posting that link.

https://www.geeksforgeeks.org/split-the-given-array-into-k-sub-arrays-such-that-maximum-sum-of-all-sub-arrays-is-minimum/

  •  Tags:  
  • Related