Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Sort Matrix by Maximum String Length
Next article icon

Python – Sort Matrix by K Sized Subarray Maximum Sum

Last Updated : 01 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given Matrix, write a Python program to sort rows by maximum of K sized subarray sum.

Examples:

Input : test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]], K = 3 
Output : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]] 
Explanation : 12 = 12 = 12 < 21, is order of maximum sum 3 length substring.

Input : test_list = [[4, 3, 5, 2, 3], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]], K = 3 
Output : [[4, 3, 5, 2, 3], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]] 
Explanation : 12 = 12 < 21, is order of maximum sum 3 length substring. 

Method #1 : Using max() + sum() + slicing + sort()

In this, maximum of K length subarray is computed using max(), sum() and slicing using external function and inplace sorting is done using sort().

Python3




# Python3 code to demonstrate working of
# Sort Matrix by K Sized Subarray Maximum Sum
# Using max() + sum() + slicing + sort()
 
 
def max_ksub(row):
 
    # getting maximum K length sum
    return max(sum(row[idx: idx + K]) for idx in range(len(row) - K))
 
 
# initializing list
test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1],
             [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 3
 
# performing inplace sorting
test_list.sort(key=max_ksub)
 
# printing result
print("The sorted result : " + str(test_list))
 
 

Output:

The original list is : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]] The sorted result : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]]

Time Complexity: O(nlogn+mlogm)
Auxiliary Space: O(1)

Method #2 : Using sorted() + lambda + max() + sum() + slicing

In this, we perform task of sorting using sorted() + lambda function which injects comparator logic and avoids calling external function.

Python3




# Python3 code to demonstrate working of
# Sort Matrix by K Sized Subarray Maximum Sum
# Using sorted() + lambda + max() + sum() + slicing
 
# initializing list
test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1],
             [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 3
 
# sorted() performs inplace sort
# lambda function injects comparison logic
res = sorted(test_list, key=lambda row: max(
    sum(row[idx: idx + K]) for idx in range(len(row) - K)))
 
# printing result
print("The sorted result : " + str(res))
 
 

Output:

The original list is : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]] The sorted result : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]]

Time Complexity: O(nlogn+mlogm)
Auxiliary Space: O(n)

Method 3: Using heapq.nlargest() + sum() + enumerate()

Python3




# Python3 code to demonstrate working of
# Sort Matrix by K Sized Subarray Maximum Sum
# Using heapq.nlargest() + sum() + enumerate()
 
# importing required module
import heapq
 
# initializing list
test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1],
             [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 3
 
# heapq.nlargest() returns the n largest elements from the iterable
# lambda function calculates the sum of K-sized subarrays of a row
# enumerate() adds index to the result of heapq.nlargest()
# sorted() sorts the rows based on their K-sized subarray maximum sum
res = sorted(test_list, key=lambda row: heapq.nlargest(1, ((sum(row[i:i+K]), i) for i in range(len(row) - K + 1)), key=lambda x: x[0])[0][1])
 
# printing result
print("The sorted result : " + str(res))
 
 
Output
The original list is : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]] The sorted result : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]]

Time complexity: O(n * k * log(n)), where n is the number of rows and k is the subarray size. 
Auxiliary space: O(n * k).



Next Article
Python - Sort Matrix by Maximum String Length
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Sort Matrix by Maximum String Length
    Given a matrix, perform row sort basis on the maximum length of the string in it. Input : test_list = [['gfg', 'best'], ['geeksforgeeks'], ['cs', 'rocks'], ['gfg', 'cs']] Output : [['gfg', 'cs'], ['gfg', 'best'], ['cs', 'rocks'], ['geeksforgeeks']] Explanation : 3 < 4 < 5 < 13, maximum leng
    3 min read
  • Python Program for Maximum size square sub-matrix with all 1s
    Write a Python program for a given binary matrix, the task is to find out the maximum size square sub-matrix with all 1s. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.Approach: Let the given binary matrix be M[R][C]. The idea of the algorithm is to construct an
    4 min read
  • Python3 Program for Size of The Subarray With Maximum Sum
    An array is given, find length of the subarray having maximum sum. Examples : Input : a[] = {1, -2, 1, 1, -2, 1}Output : Length of the subarray is 2Explanation: Subarray with consecutive elements and maximum sum will be {1, 1}. So length is 2Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 }Output : Len
    4 min read
  • Python program to Sort Matrix by Maximum Row element
    Given a Matrix, sort rows by maximum element. Input : test_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted. Input : test_list = [[9, 10, 3], [10, 18, 3], [0, 3, 5]
    4 min read
  • Python Program to Sort Matrix by Sliced Row and Column Summation
    Given a Matrix and a range of indices, the task is to write a python program that can sort a matrix on the basis of the sum of only given range of indices of each row and column i.e. the rows and columns are to sliced from a given start to end index, further, matrix are sorted using only those slice
    8 min read
  • Python | Maximum Sum Sublist
    The task is to find a contiguous sublist (i.e., a sequence of elements that appear consecutively in the original list) such that the sum of the elements in this sublist is as large as possible. We need to return the maximum sum of this sublist. Let's explore methods to find Maximum Sum Sublist in py
    2 min read
  • Python - Sort Matrix by Row Median
    Given a Matrix, sort by median of each row. Input : test_list = [[3, 4, 7], [1, 7, 2], [10, 2, 4], [8, 6, 5]] Output : [[1, 7, 2], [3, 4, 7], [10, 2, 4], [8, 6, 5]] Explanation : 2 < 3 < 4 < 6, sorted increasingly by median element. Input : test_list = [[3, 4, 7], [1, 7, 2], [8, 6, 5]] Outp
    4 min read
  • Python - Row with Minimum Sum in Matrix
    We can have an application for finding the lists with the minimum value and print it. This seems quite an easy task and may also be easy to code, but having shorthands to perform the same are always helpful as this kind of problem can come in web development. Method #1 : Using reduce() + lambda The
    4 min read
  • Python program to sort matrix based upon sum of rows
    Given a Matrix, perform sort based upon the sum of rows. Input : test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]] Output : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]] Explanation : 3 < 9 < 11 < 14. Sorted sum. Input : test_list = [[4, 5], [2, 5, 7], [4, 6, 1]] Output : [[4, 5], [4, 6, 1], [2,
    6 min read
  • Python - Sort list of lists by the size of sublists
    The problem is to sort a list of lists based on the size of each sublist. For example, given the list [[1, 2], [1], [1, 2, 3]], the sorted result should be [[1], [1, 2], [1, 2, 3]] when sorted in ascending order. We will explore multiple methods to do this in Python. Using sorted() with len() This m
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences