
The first line contains ‘T’, denoting the number of tests.
For each Test :
The first line contains an integer ‘N’, denoting the number of water balls.
The second line contains an array ‘A’ of length ‘N’, denoting the temperatures of water balls.
For each test, print an integer, denoting the maximum number of balls you can collect, such that the total temperature of the bag is non-negative at each instance.
You are not required to print the expected output. It has already been taken care of. Just implement the function.
1 <= T <= 5
1 <= N <= 10^5
-10^9 <= A[i] <= 10^9 i ∈ (1,N)
Time Limit: 1 sec
Algorithm:
Maintain a dp[ ][ ], where dp[i][j] contains the maximum possible prefix sum if ‘j’ elements are taken till index ‘i’. Here index can vary from [0 to N-1] and the count of collected elements from [0 to N], so dimensions of dp will be (N * (N+1)). Initialize the entire dp with some negative value, say -1.
Now the question arises, what are the transitions to fill the dp?
Do the above transitions for each pair (i, j), and our desired answer will be the maximum value of ‘j’ with i = N-1, for which dp[i][j] is non-negative.
Algorithm:
At any position where the current element can’t be taken, try to maximize the prefix sum. Maintain a priority queue (min-heap) to store our collected elements in non-decreasing order. If we have collected any element ‘x’ that is more negative than the current element, then subtract ‘x’ from our prefix sum and assume that we have not collected that. In place of ‘x’, we will take the current element; although it doesn’t increase the count of elements, it makes the prefix sum more positive, which can be used in further processing.
Algorithm: