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:
Largest Subset with sum less than each Array element
Next article icon

Largest Subset with sum at most K when one Array element can be halved

Last Updated : 08 Apr, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N and an integer K, the task is to find the size of the largest subset possible having a sum at most K when only one element can be halved (the halved value will be rounded to the closest greater integer).

Examples:

Input: arr[] = {4, 4, 5}, K = 15
Output: 3
Explanation: 4+4+5 = 13 which is less than 15. So subset can have all elements.

Input: arr[3] = {2, 3, 5}, K = 9
Output: 3
Explanation: 2 + 3 = 5 which is less than 9
2 + 3 + 5 = 10 which is greater than 9, So cannot be part of subset. 
After halving i.e. ceil [5/2] = 3, sum = 2+3+3 = 8 which is less than 9.
So all 3 elements can be part of subset.

Input:  arr[8] = {1, 2, 3, 4, 5, 6, 7, 8}, K = 20
Output: 6
Explanation: 1+2+3+4+5 = 15 which is less than 20
15 + 6 = 21 which is greater than 20.
After halving the value i.e. ceil [6/2] = 3
15 + 3 = 18 which is less than 20. So it can be part of subset.

 

Approach: The given problem can be solved using Sorting method based on the following idea:

In a sorted array keep on performing sum from i = 0 to N-1. If at any moment sum is greater than K, that element can only be included if after halving that value the sum is at most K

Follow the steps mentioned below to solve the problem:

  • Sort the array in ascending order.
  • Declare a variable (say Sum) to maintain the sum.
  • Traverse the array from i = 0 to N-1:
    • Add arr[i] to Sum.
    • If Sum is greater than K, then make arr[i] = ceil(arr[i]/2) and check if that sum is less than K or not.
    • If Sum is less than K then continue iteration.
    • Increment the size of the subset.
  • Return the size of the subset.

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 total number of element
int findcount(int arr[], int n, int m)
{
    int ans = n, sum = 0, count = 0;
 
    // Sort the array
    sort(arr, arr + n);
    for (int i = 0; i < n; i++) {
 
        // Round up to the ceil value
        if (sum + (arr[i] + 1) / 2 > m) {
            ans = i;
            break;
        }
        // Sum of the array elements
        sum += arr[i];
 
        // Size of the subset
        count++;
    }
    return count;
}
 
// Driver code
int main()
{
    int N = 8, K = 20;
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
 
    // Function call
    cout << findcount(arr, N, K);
    return 0;
}
 
 

Java




// JAVA program for the above approach
 
import java.util.*;
class GFG {
 
  // Function to find total number of element
  public static int findcount(int arr[], int n, int m)
  {
    int ans = n, sum = 0, count = 0;
 
    // Sort the array
    Arrays.sort(arr);
    for (int i = 0; i < n; i++) {
 
      // Round up to the ceil value
      if (sum + (arr[i] + 1) / 2 > m) {
        ans = i;
        break;
      }
      // Sum of the array elements
      sum += arr[i];
 
      // Size of the subset
      count++;
    }
    return count;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int N = 8, K = 20;
    int arr[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
 
    // Function call
    System.out.print(findcount(arr, N, K));
  }
}
 
// This code is contributed by Taranpreet
 
 

Python3




# Python solution based on above approach
 
# Function to find total number of element
def findcount(n, k, arr):
   
  # Sort the array
    arr.sort()
    sum = 0
    count = 0
    for i in range(n):
       
      # Round up to the ceil value
        if (sum + (arr[i] + 1) / 2 > k):
            ans = i
            break
             
        # Sum of the array elements
        sum += arr[i]
         
        # Size of the subset
        count = count + 1
    return(count)
     
# driver code
n = 8
k = 20
arr = [1, 2, 3, 5, 4, 6, 7, 8]
result = findcount(n,k,arr)
print(result) 
 
# This code is contributed by greeshmapslp.
 
 

C#




// C# program for the above approach
using System;
class GFG {
 
    // Function to find total number of element
    static int findcount(int[] arr, int n, int m)
    {
        int ans = n, sum = 0, count = 0;
 
        // Sort the array
        Array.Sort(arr);
        for (int i = 0; i < n; i++) {
 
            // Round up to the ceil value
            if (sum + (arr[i] + 1) / 2 > m) {
                ans = i;
                break;
            }
            // Sum of the array elements
            sum += arr[i];
 
            // Size of the subset
            count++;
        }
        return count;
    }
 
    // Driver code
    public static void Main()
    {
        int N = 8, K = 20;
        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
 
        // Function call
        Console.Write(findcount(arr, N, K));
    }
}
 
// This code is contributed by Samim Hossain Mondal.
 
 

Javascript




<script>
// JavaScript program for the above approach
 
// Function to find total number of element
function findcount(arr, n, m)
{
    var ans = n;
    var sum = 0;
    var count = 0;
 
    // Sort the array
    arr.sort();
     
    for (var i = 0; i < n; i++) {
 
        // Round up to the ceil value
        if (sum + Math.floor((arr[i] + 1) / 2) > m) {
            ans = i;
            break;
        }
        // Sum of the array elements
        sum += arr[i];
 
        // Size of the subset
        count++;
    }
    return count;
}
 
// Driver code
var N = 8;
var K = 20;
var arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ];
 
// Function call
document.write(findcount(arr, N, K));
 
// This code is contributed by phasing17
</script>
 
 
Output
6

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



Next Article
Largest Subset with sum less than each Array element
author
dragonuncaged
Improve
Article Tags :
  • Arrays
  • DSA
  • Geeks Premier League
  • Sorting
  • Geeks-Premier-League-2022
  • subset
Practice Tags :
  • Arrays
  • Sorting
  • subset

Similar Reads

  • Largest Subset with sum less than each Array element
    Given an array arr[] containing N elements, the task is to find the size of the largest subset for each array element arr[i] such that the sum of the subset is less than that element. Examples: Input: arr[] = { 5, 2, 1, 1, 1, 6, 8}Output: 3 1 0 0 0 4 4 Explanation: For i = 0 -> subset = {1, 1, 1}
    12 min read
  • Maximize number of elements from Array with sum at most K
    Given an array A[] of N integers and an integer K, the task is to select the maximum number of elements from the array whose sum is at most K. Examples: Input: A[] = {1, 12, 5, 111, 200, 1000, 10}, K = 50 Output: 4 Explanation: Maximum number of selections will be 1, 12, 5, 10 that is 1 + 12 + 5 + 1
    6 min read
  • Minimize splits in given Array to find subsets of at most 2 elements with sum at most K
    Given an array arr[] of N integers and an integer K, the task is to calculate the minimum number of subsets of almost 2 elements the array can be divided such that the sum of elements in each subset is almost K. Examples: Input: arr[] = {1, 2, 3}, K = 3Output: 2Explanation: The given array can be di
    6 min read
  • Split array into equal length subsets with maximum sum of Kth largest element of each subset
    Given an array arr[] of size N, two positive integers M and K, the task is to partition the array into M equal length subsets such that the sum of the Kth largest element of all these subsets is maximum. If it is not possible to partition the array into M equal length subsets, then print -1. Example
    7 min read
  • Split array into K subsets to maximize sum of their second largest elements
    Given an array arr[] consisting of N integers and an integer K, the task is to split the array into K subsets (N % K = 0) such that the sum of second largest elements of all subsets is maximized. Examples: Input: arr[] = {1, 3, 1, 5, 1, 3}, K = 2Output: 4Explanation: Splitting the array into the sub
    5 min read
  • Smallest number to make Array sum at most K by dividing each element
    Given an array arr[] of size N and a number K, the task is to find the smallest number M such that the sum of the array becomes lesser than or equal to the number K when every element of that array is divided by the number M.Note: Each result of the division is rounded to the nearest integer greater
    8 min read
  • Largest integers with sum of setbits at most K
    Given an array of integer nums[] and a positive integer K, the task is to find the maximum number of integers that can be selected from the array such that the sum of the number of 1s in their binary representation is at most K. Examples: Input: nums[] = [3, 9, 4, 6], K = 3Output: 2Explanation: The
    7 min read
  • Remove minimum elements from ends of array so that sum decreases by at least K | O(N)
    Given an array arr[] consisting of N elements, the task is to remove minimum number of elements from the ends of the array such that the total sum of the array decreases by at least K. Note that K will always be less than or equal to the sum of all the elements of the array. Examples: Input: arr[] =
    7 min read
  • Maximize Kth largest element after splitting the given Array at most C times
    Given an array arr[] and two positive integers K and C, the task is to maximize the Kth maximum element obtained after splitting an array element arr[] into two parts(not necessarily an integer) C number of times. Print -1 if there doesn't exist Kth maximum element. Note: It is compulsory to do spli
    7 min read
  • Maximum elements that can be removed from front of two arrays such that their sum is at most K
    Given an integer K and two arrays A[] and B[] consisting of N and M integers, the task is to maximize the number of elements that can be removed from the front of either array according to the following rules: Remove an element from the front of either array A[] and B[] such that the value of the re
    15+ 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