Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

The largest sum on a circle

Medium · Target 20 minutes · Dynamic programming · Type asked atAmazonTwo Sigma

A list of integers nums is arranged in a circle: the element after the last is the first. Return the largest sum of a non-empty contiguous stretch, which may wrap around the end, but may use each element at most once.

Examples

InputOutputWhy
nums = [5,-3,5]10Wrap around: 5 + 5.
nums = [1,-2,3,-2]3The 3 alone.
nums = [-3,-2,-3]-2All negative: the best single element, not the empty stretch.

Constraints

  • 1 ≤ nums.length ≤ 3 · 10⁴
  • −3 · 10⁴ ≤ nums[i] ≤ 3 · 10⁴

Hints

Hint 1

A wrapping stretch leaves out a contiguous middle part.

Hint 2

The best wrapping stretch is the total minus the smallest-sum ordinary stretch.

Hint 3

If every number is negative, the "wrap" would be empty: return the ordinary maximum.

Where people lose marks

  • Concatenating the list with itself and running Kadane, which can use an element twice.
  • Returning 0 (an empty stretch) when all numbers are negative.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.