Maximum Total of Nonadjacent Ratings
Problem statement
Choose zero or more indices from ratings so that no two selected indices are consecutive. Return the maximum sum of the selected ratings.
For this exercise, adjacency is by array position: selecting index i prevents selecting i-1 and i+1 when they exist. Equal or consecutive numeric rating values do not create additional exclusions. The first and last positions are not neighbors unless the array has length 2.
Ratings are nonnegative. Choosing no indices is allowed and gives 0; an empty array therefore returns 0. Return only the maximum total and leave ratings unchanged.
Function
maxNonAdjacentRatings(ratings: int[]) → intExamples
Example 1
ratings = [2,7,9,3,1]return = 12Select indices 0,2,4 with values 2,9,1 for total 12. They are pairwise nonconsecutive; no allowed selection has a higher total.
Example 2
ratings = [5,1,1,5]return = 10Select the two endpoints, indices 0 and 3, for 5+5=10. This is a linear array, so the endpoints are not adjacent.
Constraints
- For this exercise, assume 0 <= ratings.length <= 1000.
- Every rating is between 0 and 1000000, inclusive.