There are ‘N’ water balls arranged in a line. Some of them are hot water balls, and some are cold, i.e., temperatures of balls may be negative, zero or positive. You have an empty bag with you, and you will be collecting some balls in this bag, starting from left to right.
For each ball, you decide whether to collect this ball or not. Once you collect a ball, you can’t drop it, and you can’t go left from any position.
Total temperature of the bag at any moment is the sum of temperatures of water balls collected in it till that moment. Your task is to find the maximum number of balls you can collect, such that the total temperature of your bag must not go negative at any instance.
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.
Output Format:
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.
Note:
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
2
6
4 -4 1 -3 1 -3
3
2 -3 -1
5
2
For case 1:
The optimal selection is to collect balls [4, 1, -3, 1, -3], where you will be able to collect five balls. For any other selection, you can’t collect more than five balls. Hence answer is 5.
For Case 2:
Optimal selection is balls [2, -1]. Hence answer is 2.
2
3
-1 -2 1
4
0 3 2 1
1
4
Can you check for all possible selections of water balls?
Approach: We need to find the longest subsequence such that its prefix sum at each position is non-negative. Using recursion, generate all subsequences of the given array. For each subsequence, check whether its prefix sum is non-negative at each place. If the prefix sum goes negative, ignore such a sequence; otherwise, consider its length to maximize the answer.
Algorithm:
O(2 ^ N), where ‘N’ is the number of elements/water balls.
At each index, two recursive calls are taking place. Hence overall time complexity becomes O(2^N).
O(2 ^ N), where ‘N’ is the number of elements/water balls.
Apart from recursion, we are using only constant space. The space is used by stack in recursion calls only. Hence overall space complexity is O(2^N).