Skip to the code
cf.
+25 XP

#63 Circular Playlist Best Segment

medium

A music app plays a playlist on repeat. Each song has a rating change in ratings (positive is liked, negative skipped). Because the playlist loops, a segment can run off the end and continue from the start, but it can't include any song twice.

Write bestLoopSegment(ratings) that returns the largest total of a segment of at least one song.

Example 1

Input: ratings = [4,-6,3,-1,5]
Output: 11

The segment 3, -1, 5, wrapping to 4, totals 11.

Example 2

Input: ratings = [-3,-2,-5]
Output: -2

Every song is negative, so pick the single best one.

Constraints

  • 1 <= ratings.length <= 3 * 10^4
  • -3 * 10^4 <= ratings[i] <= 3 * 10^4
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).