All problems
0275MediumArrayDivide and ConquerDynamic ProgrammingQueueMonotonic Queue

Best Arc of the Ring Road

Tracked in this browser only
Write code

Trains the technique from

LeetCode 918Maximum Sum Circular Subarray

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A ring road is split into n tolled sections laid end to end around a circle and numbered 0 through n - 1, with section n - 1 running straight into section 0. ledger[i] is last quarter's net result for section i, in thousands, and it is negative on a section whose upkeep cost more than its tolls brought in.

An arc is a non-empty run of sections taken in ring order, so an arc is allowed to carry on past section n - 1 and continue at section 0. An arc may not visit a section twice, so it holds between 1 and n sections.

Return the largest net total any single arc reaches.

Examples

Example 1

Input
ledger = [5, -3, 6, -9, 4]
Output
12

The arc that begins at section 4 and carries on through sections 0, 1 and 2 totals 4 + 5 - 3 + 6 = 12.

Example 2

Input
ledger = [3, -1, 3]
Output
6

The arc holding section 2 and then section 0 totals 3 + 3 = 6.

Example 3

Input
ledger = [-4, -2, -7]
Output
-2

Section 1 on its own is an arc, and its total is -2.

Constraints

  • n == ledger.length
  • 1 <= n <= 3 * 10^4
  • -3 * 10^4 <= ledger[i] <= 3 * 10^4

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def best_ring_arc(ledger: list[int]) -> int:
Java
public int bestRingArc(int[] ledger)
September 7
Apply