
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- 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 any two numbers in a list that sums up to k in Python
- Program to find valid matrix given row and column sums in Python
- Subarray Sums Divisible by K in C++
- Program to make pairwise adjacent sums small in Python
- Program to find index whose left and right elements sums are equal in Python
- Program to find number of distinct coin sums we can make with coins and quantities in Python?
- Program to find range sum of sorted subarray sums using 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
- Program to Find K-Largest Sum Pairs in Python
- Program to count number of sublists with exactly k unique elements in Python
- Program to find minimum value to insert at beginning for all positive prefix sums in Python

Advertisements