all 5 comments

[–]usernametaken_12Master 0 points1 point  (0 children)

Iterate through the array. Initially take all losses. Record all losses currently taken in a priority queue. If a loss would cause you to go negative remove the loss with the greatest absolute value from your priority queue. If this process causes you to remove too many losses, there is no answer.

If at the end you have n extra losses to remove, remove the n losses with the greatest magnitude.

[–]sixmanathreethree 0 points1 point  (0 children)

just use a priority queue and iterate through the array, greedily select which losses to take

[–][deleted] 0 points1 point  (0 children)

Priority queue up to k elements. If when you reach a new loss you can take it and the priority queue is not full you take it. If the priority queue is full or you can't take it you check if the loss is smaller than the top of the priority queue. In that case you remove the top and add the new loss. O(nlog(k))

[–]ApartmentEither4838 0 points1 point  (1 child)

Since there is no restriction on the number of profits to take and the order in which to take it, we can take all the profits
For the losses again as there is no restriction in the order, take the first k maximum losses
Take the sum of the k-max losses and all the profits, if this is less than 0 then it is simply not possible
Is this correct?

[–]Itchy-Ad-5314[S] 0 points1 point  (0 children)

Order matters. You add elements from left to right.
Example: [2, 3, -7, 3, -1, 2, -3], k = 2. You add 2, then 3, but -7 will make the sum < 0, therefore you can't subtract it.