![]() |
VOOZH | about |
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,-3Input: 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:
Below is the implementation of the above approach:
5
Time Complexity: O(nlog(n))
Auxiliary Space: O(n)