Program to find the sum of the lengths of two nonoverlapping sublists whose sum is given in Python


Suppose we have a list of numbers called nums and another value k, we have to find two nonoverlapping sublists in nums whose sum is k, and we have to find the sum of their lengths. When there are more than two possible sublists, we have to find the sum of the lengths of the two smallest sublists. If we cannot find the answer, return −1.

So, if the input is like nums = [7, 10, −2, −1, 4, 3] k = 7, then the output will be 3, as we pick the sublists like [7] and [4, 3]. We did not pick [10, −2, −1] as this is longer.

To solve this, we will follow these steps −

  • N := size of A

  • prefix := of size N, and fill with infinity

  • last := a map with value −1 for key 0 {0: −1}

  • s := 0

  • for i in range 0 to N, do

    • s := s + A[i]

    • prefix[i] := i − last[s − target], if not found set −infinity

    • last[s] := i

  • for i in range 1 to N, do

    • prefix[i] := minimum of prefix[i], prefix[i − 1]

  • suffix := of size N, and fill with infinity

  • last := a map with value N for key 0 {0: N}

  • s := 0

  • for i in range N − 1 to −1, decrease by 1, do

    • s := s + A[i]

    • suffix[i] := last[s − target] (if not found set infinity) − i

    • last[s] := i

  • for i in range N − 2 to −1, decrease by 1, do

    • suffix[i] := minimum of suffix[i] and suffix[i + 1]

  • ans := minimum of prefix[i] + suffix[i + 1] for each i in range 0 to N − 1

  • return ans if ans < infinity otherwise −1

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, A, target):
      INF = float("inf")
      N = len(A)
      prefix = [INF] * N
      last = {0: −1}
      s = 0
      for i in range(N):
         s += A[i]
         prefix[i] = i − last.get(s − target, −INF)
         last[s] = i
      for i in range(1, N):
         prefix[i] = min(prefix[i], prefix[i − 1])
      suffix = [INF] * N
      last = {0: N}
      s = 0
      for i in range(N − 1, −1, −1):
         s += A[i]
         suffix[i] = last.get(s − target, INF) − i
         last[s] = i
      for i in range(N − 2, −1, −1):
         suffix[i] = min(suffix[i], suffix[i + 1])
      ans = min(prefix[i] + suffix[i + 1] for i in range(N − 1))
      return ans if ans < INF else −1
ob = Solution()
nums = [7, 10, −2, −1, 4, 3]
k = 7
print(ob.solve(nums, k))

Input

[7, 10, −2, −1, 4, 3], 7

Output

3

Updated on: 21-Oct-2020

66 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements