- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

# Program to find k sublists with largest sums and return sums in ascending order in Python

Suppose we have a list of numbers called nums, and another value k, we have to find k sublists with the largest sums and return the sums in non-decreasing order.

So, if the input is like nums = [2, 4, 5, -100, 12, -30, 6, -2, 6] k = 3, then the output will be [10, 11, 12], as we have these 3 sublists with the largest sums − [6, -2, 6], [2, 4, 5], [12].

To solve this, we will follow these steps −

- ps := a list of 1 + size of nums and fill with 0
- for each index i and value v nums, do
- ps[i + 1] := v + ps[i]

- hp := a new list
- for i in range 0 to size of ps, do
- for j in range i + 1 to size of ps, do
- insert -(ps[j] - ps[i]) into ps heap

- for j in range i + 1 to size of ps, do
- res := pop all elements in ps heap and reverse them
- return res

Let us see the following implementation to get better understanding −

## Example

from heapq import heappop, heappush class Solution: def solve(self, nums, k): ps = [0 for _ in range(len(nums) + 1)] for i, v in enumerate(nums): ps[i + 1] = v + ps[i] hp = [] for i in range(len(ps)): for j in range(i + 1, len(ps)): heappush(hp, -(ps[j] - ps[i])) return list(reversed([-heappop(hp) for _ in range(k)])) ob = Solution() nums = [2, 4, 5, -100, 12, -30, 6, -2, 6] k = 3 print(ob.solve(nums, k))

## Input

[2, 4, 5, -100, 12, -30, 6, -2, 6],3

## Output

[10, 11, 12]

- Related Questions & Answers
- Find K Pairs with Smallest Sums in C++
- Program to find overlapping intervals and return them in ascending order in Python
- Program to find minimum largest sum of k sublists in C++
- Program to find valid matrix given row and column sums in Python
- Program to find any two numbers in a list that sums up to k in Python
- Subarray Sums Divisible by K in C++
- Program to find index whose left and right elements sums are equal in Python
- Program to make pairwise adjacent sums small in Python
- Program to find range sum of sorted subarray sums using Python
- Program to find number of distinct coin sums we can make with coins and quantities in Python?
- Program to Find K-Largest Sum Pairs in Python
- Program to find number of sublists with sum k in a binary list in Python
- Program to find max values of sublists of size k in Python
- Array thirds with equal sums in JavaScript
- Subarray pairs with equal sums in JavaScript

Advertisements