BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Data processing and features50 of 54 in topic

838. Pick non-adjacent nodes on a ring for the largest total

MediumData processing and features Pro

Servers sit on a ring, and each one has a value for running a job on it. Two neighbouring servers share a power line, so you can never use two that are next to each other. The first and the last server are also neighbours.

Write max_ring_pick(values) that returns the largest total value you can get from a set of servers with no two adjacent on the ring. All values are non-negative; picking nothing gives 0.

Functiondef max_ring_pick(values)

Example 1

Input: max_ring_pick([2, 3, 2])

Output: 3

Explanation: Because the two 2s are neighbours on the ring.

Example 2

Input: max_ring_pick([1, 2, 3, 1])

Output: 4, from the first and third servers

Constraints

  • 1 <= len(values) <= 100,000
  • 0 <= values[i] <= 1,000
Hint 1

Solve the straight line version first.

Hint 2

The first and last nodes cannot both be used.

Hint 3

Handle a ring of one node separately.

Common mistakes
  • Running the line version once on the whole array, which can pick both ends.
  • Returning 0 for a single node.
  • Using recursion without memoisation, which is exponential.
Understand the idea

Breaking a cycle into two line problems is a common trick. The line problem is a two-state dynamic program: take means the current node is used, skip means it is not. take_new = skip_old + v, skip_new = max(take_old, skip_old). For [2, 7, 9, 3, 1] on a ring, dropping the last node gives the line [2, 7, 9, 3] with best 11 (2 + 9), and dropping the first gives [7, 9, 3, 1] with best 10, so the answer is 11.

Topics
Data processing and features
Similar questions
  • Split a dataset so every class keeps its shareMedium
  • Bin a feature into quantile buckets learned from training dataMedium
  • Frequency-encode a category with a shared bucket for rare and unseen valuesMedium
  • Generate K-fold train and validation index splitsMedium
All Data processing and features problems
Report
838 / 903
Python 3solution.pyPython idle
1
2
3
4
def max_ring_pick(values):
# values on a ring; no two picked nodes may be adjacent
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS