Codey and Speeches

https://www.hackerrank.com/contests/codenection-2024-final-round-closed-category/challenges/cn24-20

Question

Codey is feeling extra motivated today (because it is the CodeNection Final day!) and wants to give motivational speeches! Codey has found n of its friends, lined up from left to right. Codey plans to deliver speeches starting from the leftmost friend and moving to the rightmost friend. For each friend, Codey can choose whether to deliver a speech or skip them.

Giving a speech to friend i will result in receiving a feedback score of aia_i. The score aia_i can be negative because some friends might find Codey's speech boring!

Codey wants to give as many speeches as possible and stay motivated at the same time. This means that the total feedback score from the speeches delivered at any point must remain greater than or equal to 0.

Find the maximum number of speeches Codey can deliver while satisfying all the conditions!

Input Format

The first line contains an integer n, which represents the number of friends.

The second line contains nn integers, a1,a2,...,ana_1,a_2,...,a_n, each representing the feedback score of the i-th friend.

Constraints

1n1051 \le n \le 10^5
109ai109-10^9 \le a_i\le10^9

Output Format

Output an integer representing the maximum number of speeches Codey can give.

Sample Inputs:

Input

Output

Explanation

Codey will skip the first friend and give speeches to the rest of the friends. Codey cannot give a speech to the first friend because it would cause Codey to become demotivated immediately.


Solution - DP of despair

When I first attempting the question, I just thought a simple solution and got around 12/35 test cases correct.

The further I dig into multiple edge cases, the lower score I can scored to be, hence that's the reason of title of "despair".

In hugely despair, dynamic programming may become the solution, which is the final savior to save me out after three hours of fixing the code.

No matter what, the dynamic programming works as this:

  1. (Optional) use a min_heap to store negative numbers.

  2. Create a DP array, in each cell, we maintain the sum and stop at the path if it went negative.

  3. Once the path becomes negative, remove the least negative number.

  4. Use dp[i] to track the counter.

  5. The final solution will be in dp[n].

Finally, here's the solution of despair, which finally passed all test cases:

Last updated