VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-number-of-elements-that-can-be-taken/

⇱ Maximum number of elements that can be taken - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum number of elements that can be taken

Last Updated : 23 Dec, 2023

Given an array of N integers. Each i'th element increases your sum by a[i], where a[i] can be negative which may decrease your sum. You start with sum=0 and iterate the array from left to right. at each index, you may add the element to your sum or not Your task is to add the maximum number of elements in your sum, given that the sum remains non-negative.

Examples:

Input: arr = {4, -4, 1, -3, 1, -3}
Output: 5
Explanation: Take integers 4,1,-3,1,-3

Input: arr = {-3, -3, -7, -7, -1, -7, 3, 3, -2, -1, 0, -7}
Output: 5

Approach: To solve the problem follow the below idea:

The idea is to iterate through an array, adding each element to a sum and keeping track of the count, while adjusting the sum to remain non-negative by removing the most negative elements when needed. The result is the maximum number of elements that can be added to the sum without making it negative.

Step-by-step approach:

  • Start with variables for the current sum (currentSum) and the count of elements added (elementsAdded), both initially set to 0.
  • Use a priority queue (negativeElements) to store negative values.
  • Loop through each element of the array.
    • Add the current element to currentSum and increment elementsAdded.
    • Push the negative of the current element to the priority queue.
    • Check if currentSum is negative.
    • If negative, enter a loop:
      • Reduce elementsAdded.
      • Remove the most negative element from the priority queue and adjust currentSum.
      • Repeat until currentSum becomes non-negative.
  • After processing all elements, the result is the maximum number of elements that can be added to the sum while keeping it non-negative.

Below is the implementation of the above approach:


Output
5

Time Complexity: O(nlog(n))
Auxiliary Space: O(n)

Comment