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 ai. The score ai 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 n integers, a1,a2,...,an, each representing the feedback score of the i-th friend.
Constraints
Output Format
Output an integer representing the maximum number of speeches Codey can give.
Sample Inputs:
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:
(Optional) use a min_heap to store negative numbers.
Create a DP array, in each cell, we maintain the sum and stop at the path if it went negative.
Once the path becomes negative, remove the least negative number.
Use dp[i] to track the counter.
The final solution will be in dp[n].
Finally, here's the solution of despair, which finally passed all test cases:
Last updated