Largest subset of Array having sum at least 0
Last Updated :
02 Feb, 2023
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>
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
Time complexity: O( N * log N )
Auxiliary Space: O(N )
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read