Maximize Movie Ratings Without Skipping Two in a Row
OracleSoftware Engineer · OnsiteLast updated
Find the maximum possible sum of a subsequence such that no two consecutive elements from the original array are omitted.
Problem Statement
You are given an array of integers ratings representing the critic scores of a list of movies in their original release order. Movie ratings can be positive, negative, or zero.
You want to curate a list of movies to maximize the sum of their ratings. However, to maintain continuity in your catalog, you cannot skip two consecutive movies from the original list. In other words, for every adjacent pair of movies at indices i and i + 1, at least one of them must be included in your selection.
Additionally, you must select at least one movie.
Return the maximum possible sum of ratings for a valid selection.
Function Signature
def max_movie_ratings(ratings: list[int]) -> int:
pass
Input & Output Format
- Input: A list of integers
ratingsof lengthn. - Output: An integer representing the maximum total rating sum achievable.
Constraints
1 <= ratings.length <= 1_000_000-10^9 <= ratings[i] <= 10^9- Time complexity should be
O(n)and auxiliary space should beO(1).
Examples
Example 1
Input: ratings = [9, -1, -3, 4, 5]
Output: 17
Explanation:
We cannot skip both -1 and -3 because they are consecutive.
To maximize the sum, we pick 9, pick -1, skip -3, pick 4, and pick 5.
Total sum = 9 + (-1) + 4 + 5 = 17.
Example 2
Input: ratings = [-5, -2, -3]
Output: -2
Explanation:
All ratings are negative. We can skip index 0 (-5), pick index 1 (-2), and skip index 2 (-3).
No two consecutive movies are skipped, and the sum is -2.
Example 3
Input: ratings = [-10]
Output: -10
Explanation:
At least one movie must be selected, so we must pick the single movie with rating -10.
Hints
Hint 1
At each position, you face a binary choice: either include the current movie or skip it.
Hint 2
If you skip the current movie, the previous movie must have been included; if you include the current movie, the previous movie could have been either included or skipped.
Hint 3
Maintain two running variables representing the maximum sum ending at the current element where it is either picked or skipped to achieve O(1) extra space.
Follow-up questions
- How would you modify the solution to reconstruct and return the actual indices of the selected movies?
- How would the problem change if the rule allowed skipping at most k consecutive elements instead of just 1?
- If the array represented a circular list (where the last movie and the first movie are also adjacent), how would you adapt your approach?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.