Program to find the sum of largest K sublist in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums, and another value k, which represents a large list of nums concatenated k times. We have to find the sum of the contiguous sublist with the largest sum.

So, if the input is like nums = [1, 3, 4, -5], k = 1, then the output will be 11, as we can take the sublist like [2, 4, 5]

To solve this, we will follow these steps −

  • s := ans := lo := 0
  • for all value in range 0 to minimum of k and 2, do
    • for each x in nums, do
      • s := s + x
      • lo := minimum of lo, s
      • ans := maximum of ans, s - lo
  • return ans + maximum of 0 and sum of all elements of nums * maximum of 0 and (k - 2)

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums, k):
      s = ans = lo = 0
      for _ in range(min(k, 2)):
         for x in nums:
            s += x
            lo = min(lo, s)
         ans = max(ans, s - lo)
      return ans + max(0, sum(nums)) * max(0, (k - 2))
ob = Solution()
nums = [2, 4, 5, -4]
k = 1
print(ob.solve(nums, k))

Input

[2, 4, 5, -4], 1

Output

11
raja
Published on 19-Nov-2020 11:15:58
Advertisements