- Related Questions & Answers
- Program to Find K-Largest Sum Pairs in Python
- Program to find largest average of sublist whose size at least k in Python
- Program to Find Out the Largest K-Divisible Subsequence Sum in Python
- Program to find the maximum sum of circular sublist in Python
- Program to find minimum largest sum of k sublists in C++
- Program to find sum of contiguous sublist with maximum sum in Python
- Program to find longest equivalent sublist after K increments in Python
- Program to find length of longest sublist whose sum is 0 in Python
- Program to find largest sum of 3 non-overlapping sublists of same sum in Python
- Program to find size of smallest sublist whose sum at least target in Python
- Program to find sum of rectangle whose sum at most k in Python
- Program to find length of longest distinct sublist in Python
- Program to find largest sum of any path of a binary tree in Python
- Program to find largest sum of non-adjacent elements of a list in Python
- Program to check sublist sum is strictly greater than the total sum of given list Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

- for each x in nums, do
- 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 −

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

11

Advertisements