1304. Ring Quota Window

A circular conveyor carries packages whose positive weights are listed in nums, and the last position connects back to the first. A crew may grab a stretch of consecutive positions, wrapping around the end if needed; a stretch has a length from 1 to n and never counts a position twice. Given target, return the length of the shortest stretch whose total weight is at least target, or -1 if even the whole ring weighs less than target. Walk a shrinking window over the array written twice, never letting it grow past n positions, so each position enters and leaves at most twice. Target O(n) time and O(1) extra space; totals can exceed 32 bits.

Example 1

Input:
nums = [3,1,4,1,5], target = 8
Output:
2
Explanation:

The stretch made of the last and first positions, 5 and 3, wraps around the end and weighs 8, and no single position reaches 8.

Example 2

Input:
nums = [2,2,2], target = 7
Output:
-1
Explanation:

The whole ring weighs only 6, which is below the target of 7, so the answer is -1.

Example 3

Input:
nums = [5], target = 5
Output:
1
Explanation:

The only position weighs exactly 5, so a stretch of length 1 is enough.

Constraints

1 ≤ n ≤ 1000

1 ≤ nums[i] ≤ 104

1 ≤ target ≤ 1015

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…