You are given an array of whole numbers, nums, arranged in a circle: after the last number comes the first one again.
Pick one or more neighbouring numbers on that circle, using each position at most once, and add them up. Return the largest total you can get. A run may cross the end of the array and continue from the start.
Example 1
Input: nums = [4, -6, 2, 5] Output: 11 Why: 2 + 5 + 4 wraps past the end
2 more examples and the constraints
Example 2
Input: nums = [-5, 7, -2] Output: 7 Why: the 7 alone beats any longer run
Example 3
Input: nums = [-4, -1, -7] Output: -1 Why: every number is negative, so take the largest
Constraints
- 1 ≤ length of nums ≤ 30,000
- −30,000 ≤ each number ≤ 30,000
- The run must hold at least one number
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Every start, every lengthO(n²)
- Kadane, max and minO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 30,000 numbers | Verdict |
|---|---|---|---|
| Every start, every length | O(n²) | Mention it, then move on | |
| Kadane, max and min | O(n) | Best; one pass |
n = length of nums.
Edge cases to test
- All negative. [−4, −1, −7] must return −1, not 0. That is why best < 0 returns early.
- One number. [9] returns 9; a single negative number returns itself.
- The whole circle. [5, 5, 5] returns 15: the run can use every position once.
- Wrap wins. [4, −6, 2, 5] returns 11 from the wrapped run 2, 5, 4.
- Zeros. [−2, 0, −3] returns 0, a run of just the 0.
Common mistakes
- Returning total − worst when every number is negative, which gives 0, the sum of an empty run.
- Doubling the array and running plain Kadane on it, which lets a run use the same position twice.
- Starting best at 0 instead of nums[0], so an all-negative array returns 0.
How to talk through it
- 1Clarify. Must the run be non-empty? Can it use a position twice when it wraps? What range do the numbers have?
- 2Give the brute force. Every start, every length with a running sum: O(n²), too slow for 30,000.
- 3Split into two cases. The best run is in the middle, or it wraps and leaves out a middle run. Leaving out the lowest run gives the best wrap.
- 4Code both Kadanes in one loop. Track best, worst and total together, then handle the all-negative case.
- 5Test out loud. Run [−4, −1, −7], [4, −6, 2, 5] and [5, 5, 5] before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?