A user maintains a list of negative and positive ratings for movies in a collection. The user wants to choose some subsequence of movies from the collection to bring such that the following conditions are satisfied:
- Collective sum of ratings is maximal.
- The user must go through the list in order and can’t skip more than one movie in a row. In other words, the user can’t skip over two or more consecutive movies. For e.g. if ratings = [-1, -3 -2] and must include either the second number or the first and third numbers to get a maximal rating sum of -3
Eg : ratings = [-3, 2, 4, -1, -2, -5]
the maximal choices are [2, 4, -2] for a sum of 4
The problem statement asks to complete a maximizeRatings function which has list[int] ratings as an input
The code should return maximum possible rating sum for a subsequence of movies
def maximizeRatings(ratings):
n = len(ratings)
if n == 0:
return 0
elif n == 1:
return max(0, ratings[0])
elif n == 2:
return max(0, ratings[0], ratings[1], ratings[0] + ratings[1])
# Initialize dp array
dp = [0] * n
dp[0] = max(0, ratings[0])
dp[1] = max(dp[0], ratings[1], ratings[0] + ratings[1])
# Fill the dp array
for i in range(2, n):
include_current = dp[i-2] + ratings[i]
include_current_and_previous = ratings[i] + ratings[i-1] + (dp[i-3] if i >= 3 else 0)
exclude_current = dp[i-1]
dp[i] = max(include_current, include_current_and_previous, exclude_current)
# The result is the maximum value in the dp array
return dp[-1]