Maximum Total of Nonadjacent Ratings
Updated
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.
More Morgan Stanley Online Assessment questions
- Three-Resource 0/1 KnapsackOA · Seen Sep 2026
- Maximum Concurrent ProcessesOA · ONSITE INTERVIEW · Seen Sep 2026
- Count Shipment SchedulesOA · Seen Apr 2026
- Delete and EarnOA · Seen Apr 2026
- Interleave Array HalvesOA · Seen Apr 2026
- Get Patch SequenceOA · Seen Feb 2025
- String Subsequences 🐳OA · Seen Mar 2024
- Binary Tree Level OrderOA · Seen Feb 2024
- Merge IntervalsOA · Seen Feb 2024
- Format Chemical SymbolsOA · Seen Feb 2023
Similar questions at other companies
- Maximum Income from Asset TradingJefferies · OA
- Best Time to Buy and Sell StockFlexTrade · OAFlexTrade interview questions
- Count Sawtooth SubarraysHudson River Trading · OAHudson River Trading interview questions
- Count Sawtooth SubarraysTikTok · OATikTok interview questions
- Count Alternating-Parity SubarraysVisa · OAVisa interview questions
- Find Largest Sum Contiguous SubarrayCisco · OACisco interview questions
- Maximum Sum of Non-Adjacent ElementsLSEG · OALSEG interview questions
- 0/1 KnapsackConfluent · OAConfluent interview questions
- Split Array to Minimize the Largest SumInfosys · OAInfosys interview questions
- Largest Consistent Visiting GroupAuxoAI · OA
Interview reports that mention this question
Morgan Stanley interview experiences
- Morgan Stanley New Grad Technology Analyst: 2 Experiences
- Morgan Stanley Intern Oldest Loops: 5 Experiences (Part 5 of 5)
- Morgan Stanley Intern OOP Loops: 5 Experiences (Part 4 of 5)
- Morgan Stanley Intern Earlier Loops: 5 Experiences (Part 3 of 5)
- Morgan Stanley Intern Tech Rounds: 5 Experiences (Part 2 of 5)