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
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimize sum of smallest elements from K subsequences of length L
Next article icon

Minimum sum of medians of all possible K length subsequences of a sorted array

Last Updated : 13 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a sorted array arr[] consisting of N integers and a positive integer K(such that N%K is 0), the task is to find the minimum sum of the medians of all possible subsequences of size K such that each element belongs to only one subsequence.

Examples:

Input: arr[] = {1, 2, 3, 4, 5, 6}, K = 2
Output: 6
Explanation:
Consider the subsequences of size K as {1, 4}, {2, 5}, and {3, 6}.
The sum of medians of all the subsequences is (1 + 2 + 3) = 6 which is the minimum possible sum.

Input: K = 3, arr[] = {3, 11, 12, 22, 33, 35, 38, 67, 69, 71, 94, 99}, K = 3
Output: 135

Naive Approach: The given problem can be solved by generating all possible K-sized sorted subsequences and print the median of all those subsequences as the result.

Time Complexity: O(2N)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized by using the Greedy Approach for the construction of all the subsequences. The idea is to select K/2 elements from starting of the array and K/2 elements from the ending of the array such that the median always occurs in the first part. Follow the steps below to solve the problem:

  • Initialize a variable, say res that stores the resultant sum of medians.
  • Initialize a variable, say T as N/K to store the number of subsequences required and a variable D as (K + 1)/2 to store the distance between the medians.
  • Initialize a variable, say i as (D – 1) to store the index of the first median to be added to the result.
  • Iterate until the value of i < N and T > 0, and perform the following steps:
    • Add the value of arr[i] to the variable res.
    • Increment the value of i by D to get the index of the next median.
    • Decrement the value of T by 1.
  • After completing the above steps, print the value of res as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum sum of
// all the medians of the K sized sorted
// arrays formed from the given array
void sumOfMedians(int arr[], int N,
                  int K)
{
    // Stores the distance between
    // the medians
    int selectMedian = (K + 1) / 2;
 
    // Stores the number of subsequences
    // required
    int totalArrays = N / K;
 
    // Stores the resultant sum
    int minSum = 0;
 
    // Iterate from start and add
    // all the medians
    int i = selectMedian - 1;
    while (i < N and totalArrays != 0) {
 
        // Add the value of arr[i]
        // to the variable minsum
        minSum = minSum + arr[i];
 
        // Increment i by select the
        // median to get the next
        // median index
        i = i + selectMedian;
 
        // Decrement the value of
        // totalArrays by 1
        totalArrays--;
    }
 
    // Print the resultant minimum sum
    cout << minSum;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int N = sizeof(arr) / sizeof(int);
    int K = 2;
    sumOfMedians(arr, N, K);
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
public class GFG {
 
    // Function to find the minimum sum of
    // all the medians of the K sized sorted
    // arrays formed from the given array
    static void sumOfMedians(int arr[], int N, int K)
    {
        // Stores the distance between
        // the medians
        int selectMedian = (K + 1) / 2;
 
        // Stores the number of subsequences
        // required
        int totalArrays = N / K;
 
        // Stores the resultant sum
        int minSum = 0;
 
        // Iterate from start and add
        // all the medians
        int i = selectMedian - 1;
        while (i < N && totalArrays != 0) {
 
            // Add the value of arr[i]
            // to the variable minsum
            minSum = minSum + arr[i];
 
            // Increment i by select the
            // median to get the next
            // median index
            i = i + selectMedian;
 
            // Decrement the value of
            // totalArrays by 1
            totalArrays--;
        }
 
        // Print the resultant minimum sum
        System.out.println(minSum);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 4, 5, 6 };
        int N = arr.length;
        int K = 2;
        sumOfMedians(arr, N, K);
    }
}
 
// This code is contributed by Kingash.
 
 

Python3




# Python3 program for the above approach
 
# Function to find the minimum sum of
# all the medians of the K sized sorted
# arrays formed from the given array
def sumOfMedians(arr, N, K):
 
    # Stores the distance between
    # the medians
    selectMedian = (K + 1) // 2
 
    # Stores the number of subsequences
    # required
    totalArrays = N // K
 
    # Stores the resultant sum
    minSum = 0
 
    # Iterate from start and add
    # all the medians
    i = selectMedian - 1
     
    while (i < N and totalArrays != 0):
 
        # Add the value of arr[i]
        # to the variable minsum
        minSum = minSum + arr[i]
 
        # Increment i by select the
        # median to get the next
        # median index
        i = i + selectMedian
 
        # Decrement the value of
        # totalArrays by 1
        totalArrays -= 1
 
     # Print the resultant minimum sum
    print(minSum)
 
 # Driver Code
if __name__ == '__main__':
     
    arr = [ 1, 2, 3, 4, 5, 6 ]
    N = len(arr)
    K = 2
     
    sumOfMedians(arr, N, K)
 
# This code is contributed by nirajgsuain5
 
 

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
    // Function to find the minimum sum of
    // all the medians of the K sized sorted
    // arrays formed from the given array
    static void sumOfMedians(int[] arr, int N, int K)
    {
       
        // Stores the distance between
        // the medians
        int selectMedian = (K + 1) / 2;
  
        // Stores the number of subsequences
        // required
        int totalArrays = N / K;
  
        // Stores the resultant sum
        int minSum = 0;
  
        // Iterate from start and add
        // all the medians
        int i = selectMedian - 1;
        while (i < N && totalArrays != 0) {
  
            // Add the value of arr[i]
            // to the variable minsum
            minSum = minSum + arr[i];
  
            // Increment i by select the
            // median to get the next
            // median index
            i = i + selectMedian;
  
            // Decrement the value of
            // totalArrays by 1
            totalArrays--;
        }
  
        // Print the resultant minimum sum
        Console.WriteLine(minSum);
    }
  
// Driver Code
public static void Main()
{
        int[] arr = { 1, 2, 3, 4, 5, 6 };
        int N = arr.Length;
        int K = 2;
        sumOfMedians(arr, N, K);
      
}
}
 
// This code is contributed by code_hunt.
 
 

Javascript




<script>
 
// JavaScript program for the above approach
 
    // Function to find the minimum sum of
    // all the medians of the K sized sorted
    // arrays formed from the given array
    function sumOfMedians(arr, N, K)
    {
        // Stores the distance between
        // the medians
        let selectMedian = Math.floor((K + 1) / 2);
  
        // Stores the number of subsequences
        // required
        let totalArrays =  Math.floor(N / K);
  
        // Stores the resultant sum
        let minSum = 0;
  
        // Iterate from start and add
        // all the medians
        let i = selectMedian - 1;
        while (i < N && totalArrays != 0) {
  
            // Add the value of arr[i]
            // to the variable minsum
            minSum = minSum + arr[i];
  
            // Increment i by select the
            // median to get the next
            // median index
            i = i + selectMedian;
  
            // Decrement the value of
            // totalArrays by 1
            totalArrays--;
        }
  
        // Print the resultant minimum sum
       document.write(minSum);
    }
 
 
// Driver Code
 
        let arr = [ 1, 2, 3, 4, 5, 6 ];
        let N = arr.length;
        let K = 2;
        sumOfMedians(arr, N, K);   
 
</script>
 
 
Output: 
6

 

Time Complexity: O(N)
Auxiliary Space: O(1)



Next Article
Minimize sum of smallest elements from K subsequences of length L
author
hrithikgarg03188
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • Mathematical
  • median-finding
  • subsequence
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical

Similar Reads

  • Sum of minimum element of all sub-sequences of a sorted array
    Given a sorted array A of n integers. The task is to find the sum of the minimum of all possible subsequences of A.Note: Considering there will be no overflow of numbers. Examples: Input: A = [1, 2, 4, 5] Output: 29 Subsequences are [1], [2], [4], [5], [1, 2], [1, 4], [1, 5], [2, 4], [2, 5], [4, 5]
    4 min read
  • Sum of minimum element of all subarrays of a sorted array
    Given a sorted array A of n integers. The task is to find the sum of the minimum of all possible subarrays of A. Examples: Input: A = [ 1, 2, 4, 5] Output: 23 Subsequences are [1], [2], [4], [5], [1, 2], [2, 4], [4, 5] [1, 2, 4], [2, 4, 5], [1, 2, 4, 5] Minimums are 1, 2, 4, 5, 1, 2, 4, 1, 2, 1. Sum
    4 min read
  • Minimize sum of smallest elements from K subsequences of length L
    Given an array arr[] of size N, the task is to find the minimum possible sum by extracting the smallest element from any K subsequences from arr[] of length L such that each of the subsequences have no shared element. If it is not possible to get the required sum, print -1. Examples: Input: arr[] =
    5 min read
  • Maximum sum subsequence of length K | Set 2
    Given an array sequence arr[] i.e [A1, A2 …An] and an integer k, the task is to find the maximum possible sum of increasing subsequence S of length k such that S1<=S2<=S3………<=Sk. Examples: Input: arr[] = {-1, 3, 4, 2, 5}, K = 3Output: 3 4 5Explanation: Subsequence 3 4 5 with sum 12 is the s
    7 min read
  • Maximum of minimum difference of all pairs from subsequences of given size
    Given an integer array arr[], the task is to find a subsequence of size k such that the minimum difference between any two of them is maximum. Return this largest minimum difference. Examples: Input: arr[] = [1, 2, 3, 5], k = 3Output: 2Explanation: Possible subsequences of size 3 are [1, 2, 3], [1,
    10 min read
  • Sum of all subsequences of length K
    Given an array arr[]and an integer K, the task is to find the sum of all K length subsequences from the given array. Example: Input: arr[] = {2, 3, 4}, K = 2 Output: 18 Explanation: There are 3 possible subsequences of length 2 which are {2, 3}, {2, 4} and {3, 4} The sum of all 2 length subsequences
    6 min read
  • Minimize the number of strictly increasing subsequences in an array | Set 2
    Given an array arr[] of size N, the task is to print the minimum possible count of strictly increasing subsequences present in the array. Note: It is possible to swap the pairs of array elements. Examples: Input: arr[] = {2, 1, 2, 1, 4, 3}Output: 2Explanation: Sorting the array modifies the array to
    6 min read
  • Maximize sum of second minimums of each K length partitions of the array
    Given an array A[] of size N and a positive integer K ( which will always be a factor of N), the task is to find the maximum possible sum of the second smallest elements of each partition of the array by partitioning the array into (N / K) partitions of equal size. Examples: Input: A[] = {2, 3, 1, 4
    6 min read
  • Mean of minimum of all possible K-size subsets from first N natural numbers
    Given two positive integers N and K, the task is to find the mean of the minimum of all possible subsets of size K from the first N natural numbers. Examples: Input: N = 3, K = 2Output: 1.33333Explanation:All possible subsets of size K are {1, 2}, {1, 3}, {2, 3}. The minimum values in all the subset
    7 min read
  • Number of K length subsequences with minimum sum
    Given an array arr[] of size N and an integer K, the task is to find the number of K length subsequences of this array such that the sum of these subsequences is the minimum possible. Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 1 Subsequences of length 2 are (1, 2), (1, 3), (1, 4), (2, 3),
    8 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