
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Sum of Largest K Sublist in Python
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 −
Example
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
Advertisements