← DiffPush

Longest subarray with given sum

Baseline Arrays · Easy O(n) · O(1)

Longest Window of Metered Throughput

A metering gateway logs bytes moved per second as strictly positive counters, and the billing team needs the widest contiguous window whose total traffic equals a target quota exactly. Because every counter is positive, stretching a window can only increase its total, which the search may exploit.

Input: An integer n, an array A of n positive integers, and an integer K, the target window total.

Output: The number of seconds in the longest contiguous window whose total equals K, or 0 when no such window exists.

Constraints

Examples

Example 1

Input: {"n":7,"K":3,"A":[1,2,3,1,1,1,1]}
Output: 3
The windows [1,2], [3] and [1,1,1] all total 3, and the longest of them spans three seconds.

Example 2

Input: {"n":3,"K":5,"A":[1,2,3]}
Output: 2
Only the trailing pair [2,3] reaches the quota, giving a window of length 2.

Solve this in your browser →

Also on LeetCode ↗