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 at most K when one Array element can be halved
Next article icon

Largest subset of Array having sum at least 0

Last Updated : 02 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] that contains N integers, the task is to find the largest subset having sum at least 0.

Examples:

Input: arr[] = {5, -7, 0, -5, -3, -1}
Output: 4
Explanation: The largest subset that can be selected is {5, 0, -3, -1}. It has size 4

Input: arr[] = {1, -4, -2, -3}
Output: 1

 

Naive Approach: The basic idea to solve the problem is by using Recursion based on the following idea:

At every index, there are two choices, either select that element or not. If sum is becoming negative then don’t pick it otherwise pick it. And from every recursion return the size of the largest possible subset between the two choices.

Follow the steps mentioned below:

  • Use a recursive function and for each index there are two choices either select that element or not.
  • Avoid selecting that element, whose value make the sum negative.  
  • Return the count of maximum picked elements out of both choices.
  • The maximum among all of these is the required subset size.

Below is the implementation of the above approach:

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to return maximum count
int pick_max_elements(int pos, int sum,
                      int n, int arr[])
{
 
    // Return if the end of the array
    // is reached
    if (pos == n)
        return 0;
 
    int taken = INT_MIN;
 
    // If we select element at index pos
    if (sum + arr[pos] >= 0)
        taken = 1
                + pick_max_elements(pos + 1,
                                    sum + arr[pos],
                                    n, arr);
 
    int not_taken
        = pick_max_elements(pos + 1,
                            sum, n, arr);
 
    // Return the maximize steps taken
    return max(taken, not_taken);
}
 
// Driver code
int main()
{
    int arr[] = { 1, -4, -2, -3 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function to pick maximum number
    // of elements
    cout << pick_max_elements(0, 0, N, arr);
    return 0;
}
 
 

Java




// Java code to implement the approach
import java.util.*;
class GFG
{
 
  // Function to return maximum count
  public static int pick_max_elements(int pos, int sum,
                                      int n, int arr[])
  {
 
    // Return if the end of the array
    // is reached
    if (pos == n)
      return 0;
 
    int taken = Integer.MIN_VALUE;
 
    // If we select element at index pos
    if (sum + arr[pos] >= 0)
      taken = 1
      + pick_max_elements(
      pos + 1, sum + arr[pos], n, arr);
 
    int not_taken
      = pick_max_elements(pos + 1, sum, n, arr);
 
    // Return the maximize steps taken
    return Math.max(taken, not_taken);
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int arr[] = { 1, -4, -2, -3 };
    int N = arr.length;
 
    // Function to pick maximum number
    // of elements
    System.out.print(pick_max_elements(0, 0, N, arr));
  }
}
 
// This code is contributed by Taranpreet
 
 

Python




# Python code to implement the approach
INT_MIN = -(1e9 + 7)
 
# Function to return maximum count
def pick_max_elements(pos, sum, n, arr):
 
    # Return if the end of the array
    # is reached
    if (pos == n):
        return 0
 
    taken = INT_MIN
 
    # If we select element at index pos
    if (sum + arr[pos] >= 0):
        taken = 1 + pick_max_elements(pos + 1, sum + arr[pos], n, arr)
 
    not_taken = pick_max_elements(pos + 1, sum, n, arr)
 
    # Return the maximize steps taken
    return max(taken, not_taken)
 
# Driver code
arr = [1, -4, -2, -3]
N = len(arr)
 
# Function to pick maximum number
# of elements
print(pick_max_elements(0, 0, N, arr))
 
# This code is contributed by Samim Hossain Mondal.
 
 

C#




// C# code to implement the approach
using System;
class GFG {
 
  // Function to return maximum count
  public static int pick_max_elements(int pos, int sum,
                                      int n, int[] arr)
  {
 
    // Return if the end of the array
    // is reached
    if (pos == n)
      return 0;
 
    int taken = Int32.MinValue;
 
    // If we select element at index pos
    if (sum + arr[pos] >= 0)
      taken = 1
      + pick_max_elements(
      pos + 1, sum + arr[pos], n, arr);
 
    int not_taken
      = pick_max_elements(pos + 1, sum, n, arr);
 
    // Return the maximize steps taken
    return Math.Max(taken, not_taken);
  }
 
  // Driver code
  public static void Main(string[] args)
  {
    int[] arr = { 1, -4, -2, -3 };
    int N = arr.Length;
 
    // Function to pick maximum number
    // of elements
    Console.Write(pick_max_elements(0, 0, N, arr));
  }
}
 
// This code is contributed by ukasp.
 
 

Javascript




<script>
    // JavaScript code for the above approach
 
    // Function to return maximum count
    function pick_max_elements(pos, sum,
        n, arr) {
 
        // Return if the end of the array
        // is reached
        if (pos == n)
            return 0;
 
        let taken = Number.MIN_VALUE;
 
        // If we select element at index pos
        if (sum + arr[pos] >= 0)
            taken = 1
                + pick_max_elements(pos + 1,
                    sum + arr[pos],
                    n, arr);
 
        let not_taken
            = pick_max_elements(pos + 1,
                sum, n, arr);
 
        // Return the maximize steps taken
        return Math.max(taken, not_taken);
    }
 
    // Driver code
 
    let arr = [1, -4, -2, -3];
    let N = arr.length;
 
    // Function to pick maximum number
    // of elements
    document.write(pick_max_elements(0, 0, N, arr));
 
    // This code is contributed by Potta Lokesh
</script>
 
 
Output
1

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

Efficient Approach: The efficient approach is using multiset based on the following idea:

Traverse from start of array and if at any index the sum till now becomes negative then erase the minimum element till current index from the subset. This will increase the subset sum. 
To efficiently find the minimum multiset is used.

Follow the illustration given below for a better understanding.

Illustration:

Consider the array arr[] = {1, -4, -2, -3}  

multiset <int>  s,

-> Insert arr[0] in s. s = {1}. sum = sum + arr[0] = 1

-> Insert arr[1] in s. s = { -4, 1 }. sum = sum + arr[1] = -3 
-> Remove the smallest element (i.e. -4). sum = -3 – (-4) = 1.

-> Insert arr[2] in s. s = { -2, 1 }. sum = sum + arr[2] = -1 
-> Remove the smallest element (i.e. -2). sum = -1 – (-2) = 1.

-> Insert arr[3] in s. s = { -3, 1 }. sum = sum + arr[1] = -2 
-> Remove the smallest element (i.e. is -3). sum = -2 – (-3) = 1.

Total 1 element in the subset

 Follow the below steps to solve this problem: 

  • Iterate from i = 0 to N 
    • Increment the count
    • Add the current element to the subset sum.
    • Insert arr[i] into the set.
    • If sum becomes negative then subtract the smallest value from the set and also remove the smallest element from the set
    • Decrement the count
  • Return the final count.

Below is the implementation of the above approach:

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to return max count
int pick_max_elements(int arr[], int n)
{
    int cnt = 0, sum = 0;
 
    // To store elements in sorted order
    multiset<int> s;
 
    for (int i = 0; i < n; i++) {
        sum += arr[i];
 
        // An element added,
        // so increase the cnt
        cnt++;
        s.insert(arr[i]);
        if (sum < 0) {
            sum = sum - *s.begin();
 
            // To remove the
            // smallest element
            s.erase(s.begin());
 
            // Removed an element,
            // so decrease the cnt
            cnt--;
        }
    }
    return cnt;
}
 
// Driver code
int main()
{
    int arr[] = { 1, -4, -2, -3 };
 
    // Size of array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function to pick
    // maximum number of elements
    cout << pick_max_elements(arr, N);
    return 0;
}
 
 

Java




// JAVA code to implement the above approach
import java.util.*;
class GFG {
 
// Function to return max count
static int pick_max_elements(int arr[], int n)
{
    int cnt = 0, sum = 0;
 
    // To store elements in sorted order
    Vector<Integer> s = new Vector<>();
 
    for (int i = 0; i < n; i++) {
        sum += arr[i];
 
        // An element added,
        // so increase the cnt
        cnt++;
        s.add(arr[i]);
        if (sum < 0) {
            sum = sum - s.get(0);
 
            // To remove the
            // smallest element
            s.remove(0);
 
            // Removed an element,
            // so decrease the cnt
            cnt--;
        }
    }
    return cnt;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, -4, -2, -3 };
    int N = arr.length;
 
    // Function to pick maximum number
    // of elements
    System.out.print(pick_max_elements(arr, N));
}
}
 
// This code is contributed by sanjoy_62.
 
 

Python3




# Python3 code to implement the approach
 
# using bisect.insort() to
# store elements in sorted form
import bisect
 
# Function to return max count
def pick_max_elements(arr, n) :
    cnt = 0
    sum = 0
 
    # To store elements in sorted order
    s = []
 
    for i in range(0,n) :
        sum += arr[i]
 
        # An element added,
        # so increase the cnt
        cnt += 1
        bisect.insort(s, arr[i])
         
        if sum < 0 :
            sum = sum - s[0]
 
            # To remove the
            # smallest element
             
            s.pop(0)
 
            # Removed an element,
            # so decrease the cnt
            cnt -= 1
    return cnt
 
# Driver code
if __name__ == "__main__":
 
    arr = [ 1, -4, -2, -3 ]
    N = len(arr)
     
    # Function to pick maximum number
    # of elements
    print(pick_max_elements(arr, N))
 
# This code is contributed by Pushpesh Raj
 
 

C#




// Include namespace system
using System;
using System.Collections.Generic;
 
public class GFG
{
    // Function to return max count
    public static int pick_max_elements(int[] arr, int n)
    {
        var cnt = 0;
        var sum = 0;
        // To store elements in sorted order
        var s = new List<int>();
        for (int i = 0; i < n; i++)
        {
            sum += arr[i];
            // An element added,
            // so increase the cnt
            cnt++;
            s.Add(arr[i]);
            if (sum < 0)
            {
                sum = sum - s[0];
                // To remove the
                // smallest element
                s.RemoveAt(0);
                // Removed an element,
                // so decrease the cnt
                cnt--;
            }
        }
        return cnt;
    }
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr = {1, -4, -2, -3};
        var N = arr.Length;
       
        // Function to pick maximum number
        // of elements
        Console.Write(GFG.pick_max_elements(arr, N));
    }
}
 
// This code is contributed by dhanshriborse561
 
 

Javascript




// Javascript code to implement the approach
 
    // Function to return max count
    const pickMaxElements = (arr) => {
      let cnt = 0, sum = 0;
       // To store elements in sorted order
      const s = new Set();
     
      for (let i = 0; i < arr.length; i++) {
    sum += arr[i];
    // An element added,
    // so increase the cnt
    cnt++;
    s.add(arr[i]);
    if (sum < 0) {
      sum = sum - Math.min(...s);
      // To remove the
      // smallest element
      s.delete(Math.min(...s));
      // Removed an element,
      // so decrease the cnt
      cnt--;
    }
      }
      return cnt;
    }
    // Driver code
    const arr = [1, -4, -2, -3];
     
    // Function to pick
    // maximum number of elements
    console.log(pickMaxElements(arr));
     
    // This code is contributed by Utkarsh
 
 
Output
1

Time complexity: O( N * log N )
Auxiliary Space: O(N )



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

P

patilnainesh911
Improve
Article Tags :
  • Arrays
  • DSA
  • Geeks Premier League
  • Greedy
  • Recursion
  • cpp-multiset
  • Geeks-Premier-League-2022
  • subset
Practice Tags :
  • Arrays
  • Greedy
  • Recursion
  • subset

Similar Reads

  • Largest sum subarray of size at least k
    Given an array and an integer k, the task is to find the sum of elements of a subarray containing at least k elements which has the largest sum. Examples: Input : arr[] = {-4, -2, 1, -3}, k = 2Output : -1Explanation : The sub array is {-2, 1}. Input : arr[] = {1, 1, 1, 1, 1, 1} , k = 2Output : 6 Exp
    14 min read
  • 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
  • Largest subset with composite sum in given Array
    Given an array arr[] consisting of n distinct positive integers. Find the length of the largest subset in the given array which sums to a composite number and print the required array(order or printing elements does not matter). Note: In case of multiple subsets with this largest size with the compo
    10 min read
  • Largest Subset with sum at most K when one Array element can be halved
    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 = 15Output: 3Explanation: 4
    5 min read
  • Largest pair sum in an array
    Given an unsorted of distinct integers, find the largest pair sum in it. For example, the largest pair sum is 74. If there are less than 2 elements, then we need to return -1. Input : arr[] = {12, 34, 10, 6, 40}, Output : 74 Input : arr[] = {10, 10, 10}, Output : 20 Input arr[] = {10}, Output : -1 [
    10 min read
  • Largest subarray having sum greater than k
    Given an array of integers and a value k, the task is to find the length of the largest subarray having a sum greater than k. Examples: Input: arr[] = [-2, 1, 6, -3], k = 5Output: 2Explanation: The largest subarray with a sum greater than 5 is {1, 6}. Input: arr[] = [2, -3, 3, 2, 0, -1], k = 3Output
    15 min read
  • Subset sum problem where Array sum is at most N
    Given an array arr[] of size N such that the sum of all the array elements does not exceed N, and array queries[] containing Q queries. For each query, the task is to find if there is a subset of the array whose sum is the same as queries[i]. Examples: Input: arr[] = {1, 0, 0, 0, 0, 2, 3}, queries[]
    10 min read
  • Subset array sum by generating all the subsets
    Given an array of size N and a sum, the task is to check whether some array elements can be added to sum to N . Note: At least one element should be included to form the sum.(i.e. sum cant be zero) Examples: Input: array = -1, 2, 4, 121, N = 5 Output: YES The array elements 2, 4, -1 can be added to
    5 min read
  • Longest subsequence having maximum sum
    Given an array arr[] of size N, the task is to find the longest non-empty subsequence from the given array whose sum is maximum. Examples: Input: arr[] = { 1, 2, -4, -2, 3, 0 } Output: 1 2 3 0 Explanation: Sum of elements of the subsequence {1, 2, 3, 0} is 6 which is the maximum possible sum. Theref
    8 min read
  • Longest subarray having sum of elements atmost K
    Given an array arr[] of size N and an integer K, the task is to find the length of the largest subarray having the sum of its elements at most K, where K > 0. Examples: Input: arr[] = {1, 2, 1, 0, 1, 1, 0}, k = 4Output: 5Explanation: {1, 2, 1} => sum = 4, length = 3 {1, 2, 1, 0}, {2, 1, 0, 1}
    12 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