Maximum Sum Circular Subarray

MediumArrays & Hashinggreedy

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an integer array nums that should be treated as **circular**: the element after nums[n-1] is nums[0]. Return the largest possible sum of a non-empty subarray of this circular array. A subarray may wrap around the end, but it may include each position of nums at most once (so its length is at most n). Target O(n) time and O(1) extra space.

Examples

Input: nums = [1,-2,3,-2]
Output: 3
The subarray [3].
Input: nums = [5,-3,5]
Output: 10
Wrap around: [5,5] (last element then first).
Input: nums = [-3,-2,-3]
Output: -2
All values are negative; the best non-empty subarray is [-2].

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More greedy problems