Largest subsequence such that its prefix sum never gets negative - GeeksforGeeks

27 Jan, 2022
Given an array arr[] containing integers. The task is to find the largest subsequence such that at any point in time prefix sum of that subsequence is not negative.
Examples:
Input: arr[] = {-3, -3, -7, -7, -1, -7, 3, 3, -2, -1, 0, -7}Output: 3 3 -2 -1 0Explanation: Adding -3 makes sum negative so it can’t be included, Similarly -3, -7, -7, -1, -7, -7 can’t be included. Only 3, 3, -2, -1, 0 can be included.
Input: arr[] = {3, 4, -8, 6, -7, 5}Output: 3 4 6 -7 5Explanation: 3, 4 can be added as they make sum positive but when -8 is added the sum becomes negative so it can’t be included rest all numbers can be included.
Approach: This problem can be solved by using Min Heap. Follow the steps below to solve the given problem. 
At first Initialize variables ‘s’=0 and ‘c’=0, to store the sum of array elements and count of elements respectively.
Take a min priority queue, to store the negative elements.
Now start from the leftmost element take the sum of the current element, push it to vector, and increase the count.
If the current element is less than zero push it in the min priority queue.
If the sum becomes less than zero then subtract the largest negative number(or smallest number ) of priority queue from sum and pop that element from the priority queue and also decrease the count of the element, as well as delete that element from the vector.
After traversing the whole array we get the desired subsequence in vector.
Below is the implementation of the above approach.
C++
Python3
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to find the largest subsequence// satisfying given conditionsvoid FindMaxSubsequence(int* a, int n){    // Min priority queue    priority_queue<int, vector<int>,                   greater<int> >        v;     int c = 0, s = 0;     vector<int> v1;    vector<int>::iterator it;     for (int i = 0; i < n; i++) {        // Current sum        s += a[i];         // Push the subsequence        v1.push_back(a[i]);         // Current count        c++;         // Storing negative elements        // in priority queue        if (a[i] < 0)            v.push(a[i]);         // If sum is less than zero        // than subtract largest        // negative number from left        // and decrease the count        if (s < 0) {            s -= v.top();            it = find(v1.begin(), v1.end(), v.top());             // Erase the added vector            v1.erase(it);            v.pop();            c--;        }    }     // Largest subsequence    for (auto i : v1) {        cout << i << " ";    }} // Driver Codeint main(){     int arr[] = { -3, -3, -7, -7, -1, -7,                  3, 3, -2, -1, 0, -7 };     int N = sizeof(arr) / sizeof(arr[0]);     // Function Call    FindMaxSubsequence(arr, N);    return 0;}
# Python code for the above approachfrom queue import PriorityQueue # Function to find the largest subsequence# satisfying given conditionsdef FindMaxSubsequence(a, n):     # Min priority queue    v = PriorityQueue()     c = 0    s = 0    v1 = []     for i in range(n):        # Current sum        s += a[i]         # Push the subsequence        v1.append(a[i])         # Current count        c = c + 1         # Storing negative elements        # in priority queue        if a[i] < 0:            v.put(a[i])         # If sum is less than zero        # than subtract largest        # negative number from left        # and decrease the count        if (s < 0):            t = v.get()            s = s-t            # Erase the added vector            v1.remove(t)             c = c - 1     # Largest subsequence    for i in range(len(v1)):        print(v1[i], end = " ") # Driver Codearr = [-3, -3, -7, -7, -1, -7,       3, 3, -2, -1, 0, -7] N = len(arr) # Function CallFindMaxSubsequence(arr, N) # This code is contributed by Potta Lokesh
  
3 3 -2 -1 0 
 
Time Complexity: O(N logN) Auxiliary Space: O(N)
 
lokeshpotta20
sumitgumber28
prefix
subsequence
Arrays
Greedy
Arrays
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3
Write a program to print all permutations of a given string