Program to find largest sum of 3 non-overlapping sublists of same sum in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums and another value k, we have to find the largest sum of three non-overlapping sublists of the given list of size k.

So, if the input is like nums = [2, 2, 2, -6, 4, 4, 4, -8, 3, 3, 3] k = 3, then the output will be 27, as we can select the sublists [2, 2, 2], [4, 4, 4], and [3, 3, 3], total sum is 27.

To solve this, we will follow these steps −

  • P := [0]
  • for each x in A, do
    • insert P[-1] + x at the end of P
  • Q := [P[i + K] - P[i] for i in range 0 to size of P - K]
  • prefix := Q[from index 0 to end]
  • suffix := Q[from index 0 to end]
  • for i in range 0 to size of Q - 1, do
    • prefix[i + 1] := maximum of prefix[i + 1], prefix[i]
    • suffix[~(i + 1) ] := maximum of suffix[~(i + 1) ], suffix[~i]
  • ret = (Q[i] + prefix[i - K] + suffix[i + K]) for each i in range K to size of Q - K - 1
  • return maximum of ret

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
   def solve(self, A, K):
      P = [0]
      for x in A:
         P.append(P[-1] + x)
      Q = [P[i + K] - P[i] for i in range(len(P) - K)]
      prefix = Q[:]
      suffix = Q[:]
      for i in range(len(Q) - 1):
         prefix[i + 1] = max(prefix[i + 1], prefix[i])
         suffix[~(i + 1)] = max(suffix[~(i + 1)], suffix[~i])
      return max(Q[i] + prefix[i - K] + suffix[i + K] for i in range(K, len(Q) - K))
ob = Solution()
nums = [2, 2, 2, -6, 4, 4, 4, -8, 3, 3, 3]
k = 3
print(ob.solve(nums, k))

Input

[2, 2, 2, -6, 4, 4, 4, -8, 3, 3, 3], 3

Output

27
raja
Published on 12-Dec-2020 10:26:38
Advertisements