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 −
Let us see the following implementation to get better understanding −
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))
[2, 4, 5, -4], 1