progress

~/problems / 1-D dynamic programming / Intro DP

Maximum Sum Circular Subarray

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~25 min

nums is arranged in a circle: after the last element comes the first one again. A run is a non-empty stretch of consecutive elements going around the circle, and it may wrap past the end back to the start, but it can use each element at most once.

Write max_circular_run(nums: list[int]) -> int that returns the largest sum of any run.

max_circular_run([5, -3, 5])         # 10   5, then wrap to the first 5
max_circular_run([2, -1, 3, -9, 4])  # 8    4, 2, -1, 3 (wrapping)
max_circular_run([1, -2, 3, -2])     # 3    just the 3
max_circular_run([-4, -1, -6])       # -1   the run can't be empty

Constraints: 1 <= len(nums) <= 10^5, -10^4 <= nums[i] <= 10^4.

⭐ Bonus: a speed test with 100,000 numbers earns a star in O(n) time and O(1) extra space. Trying every start and length is O(n²).

Show hint

A run that wraps around leaves out one ordinary (non-wrapping) stretch in the middle. Making the run large means making what it leaves out small.

Topic: Intro DP. State, transition, base case; top-down memo vs bottom-up table.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc