Skip to content
Related Articles

Related Articles

Sum of maximum and minimum of Kth subset ordered by increasing subset sum
  • Difficulty Level : Medium
  • Last Updated : 27 Sep, 2020

Given an integer N and set of all non-negative powers of N as S = {N0, N1, N2, N3, … }, arrange all non-empty subsets of S in increasing order of subset sum. The task is to find the sum of the greatest and smallest elements of the Kth subset from that ordering.

Examples:

Input: N = 4, K = 3
Output: 5
Explanation: 
S = {1, 4, 16, 64, … }.
Therefore, the non-empty subsets arranged in increasing order of their sum = {{1}, {4}, {1, 4}, {16}, {1, 16}, {4, 16}, {1, 4, 16}………}. 
So the elements of the subset at Kth(3rd) subset are {1, 4}. So the sum of the greatest and smallest element of this subset = (4 + 1) = 5.

Input: N = 3, K = 4
Output: 18
Explanation:
S = {1, 3, 9, 27, 81, …}.
Therefore, the non-empty subsets arranged in increasing order of their sum = {{1}, {3}, {1, 3}, {9}, {1, 9}, {3, 9}, {1, 3, 9} ……..}.
So the element in the subset at 4th position is {9}. So the sum of greatest and smallest element of this subset = (9 + 9) = 18.

 

Approach: This approach is based on the concept of Power-set. Follow the steps below to solve the problem:



  1. Generate the corresponding binary expression of the integer K (i.e., the position of the subset) in inverse order to maintain the increasing sum of elements in the subset.
  2. Then calculate whether there will be an element in the subset at corresponding positions depending on the bits present in lst[] list at successive positions.
  3. Iterate over the lst[] and if lst[i] is 0, then ignore that bit, otherwise (Ni)*lst[i] will be in the Kth Subset num[].
  4. Then the sum is calculated by taking the element of the num[] at position 0 and at the last position.
  5. Print the resultant sum after the above steps.

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 sum of greatest
// and smallest element of Kth Subset
void sumofExtremes(int N, int K)
{
  
    // Stores the binary equivalent
    // of k in inverted order
    list<int> lst;
  
    while (K > 0)
    {
        lst.push_back(K % 2);
        K = K / 2;
    }
  
    // Stores the kth subset
    list<int> num;
  
    int x = 0;
  
    // Iterate over the list
    for(auto element : lst)
    {
          
        // If the element is non-zero
        if (element != 0) 
        {
            int a = pow(N, x);
            a = a * (element);
            num.push_back(a);
        }
        x++;
    }
      
    // Update S to length of num
    int s = num.size();
  
    // If length of the subset is 1
    if (s == 1)
  
        // Print twice of that element
        cout << (2 * num.front()) << "\n";
  
    // Print the sum of first and
    // last element
    else
        cout << num.front() + num.back();
}
  
// Driver Code
int main()
{
      
    // Given number N
    int N = 4;
  
    // Given position K
    int K = 6;
  
    sumofExtremes(N, K);
}
  
// This code is contributed by akhilsaini

Java




// Java program for the above approach
import java.io.*;
import java.util.*;
  
class GFG{
  
// Function to find the sum of greatest
// and smallest element of Kth Subset
public static void sumofExtremes(int N, int K)
{
      
    // Stores the binary equivalent
    // of k in inverted order
    List<Integer> lst = new ArrayList<Integer>();
  
    while (K > 0
    {
        lst.add(K % 2);
        K = K / 2;
    }
  
    // Stores the kth subset
    List<Integer> num = new ArrayList<Integer>();
  
    int x = 0;
  
    // Iterate over the list
    for(int element : lst)
    {
          
        // If the element is non-zero
        if (element != 0
        {
            int a = (int)Math.pow(N, x);
            a = a * (element);
            num.add(a);
        }
        x++;
    }
      
    // Update S to length of num
    int s = num.size();
  
    // If length of the subset is 1
    if (s == 1)
  
        // Print twice of that element
        System.out.println(2 * num.get(0));
  
    // Print the sum of first and
    // last element
    else
        System.out.println(num.get(0) + 
                           num.get(s - 1));
}
  
// Driver Code
public static void main(String[] args)
{
      
    // Given number N
    int N = 4;
  
    // Given position K
    int K = 6;
  
    // Function call
    sumofExtremes(N, K);
}
}
  
// This code is contributed by akhilsaini

Python3




# Python3 program for the above approach
  
# Function to find the sum of greatest
# and smallest element of Kth Subset
def sumofExtremes(N, K):
  
    # Stores the binary equivalent
    # of k in inverted order
    lst = []
  
    while K > 0:
        lst.append(K % 2)
        K = K//2
  
    # Stores the kth subset
    num = []
      
    # Iterate over the list
    for i in range(0, len(lst)):
          
        # If the element is non-zero
        if(lst[i] != 0):
            a = N**i
            a = a * lst[i]
            num.append(a)
      
    # Update S to length of num
    s = len(num)
  
    # If length of the subset is 1
    if(s == 1):
  
        # Print twice of that element
        print(2 * num[0])
  
  
    # Print the sum of first and
    # last element
    else:
        print(num[0] + num[s - 1])
  
  
# Driver Code
  
# Given number N
N = 4
  
# Given position K
K = 6
  
# Function Call
sumofExtremes(N, K)

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function to find the sum of greatest
// and smallest element of Kth Subset
public static void sumofExtremes(int N, int K)
{
      
    // Stores the binary equivalent
    // of k in inverted order
    List<int> lst = new List<int>();
  
    while (K > 0) 
    {
        lst.Add(K % 2);
        K = K / 2;
    }
  
    // Stores the kth subset
    List<int> num = new List<int>();
  
    // Iterate over the list
    for(int i = 0; i < lst.Count; i++)
    {
          
        // If the element is non-zero
        if (lst[i] != 0) 
        {
            int a = (int)Math.Pow(N, i);
            a = a * (lst[i]);
            num.Add(a);
        }
    }
      
    // Update S to length of num
    int s = num.Count;
  
    // If length of the subset is 1
    if (s == 1)
  
        // Print twice of that element
        Console.WriteLine(2 * num[0]);
  
    // Print the sum of first and
    // last element
    else
        Console.WriteLine(num[0] + num[s - 1]);
}
  
// Driver Code
static public void Main()
{
      
    // Given number N
    int N = 4;
  
    // Given position K
    int K = 6;
  
    // Function call
    sumofExtremes(N, K);
}
}
  
// This code is contributed by akhilsaini
Output: 
20



 

Time Complexity: O(log K)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :