All practice tasks

Coding (Algo)

Find the Longest Range Within Budget

Prefix sum · Hard

A ledger records positive charges and negative refunds in time order. A report needs the longest uninterrupted period whose net charge stays within a chosen budget. Refunds mean that adding another entry can reduce the total, so a positive-only sliding window would be invalid.

Return the greatest length of a non-empty contiguous segment whose signed sum is at most target or zero when no segment qualifies.

Input

Call

  • Implement solve(input) and return the result. The provided adapter handles JSON input and output.

Input shape

{ nums: integer[], target: integer }

Fields

  • nums contains signed integer adjustments in their original order; target is a signed threshold.
  • A segment is a non-empty consecutive range of indexes. Negative values cannot be discarded or replaced by absolute values.

Output

Return value

  • Return an integer length, not a sum or pair of indexes. A sum exactly equal to target qualifies.
  • Empty input or no qualifying non-empty segment returns zero. The best segment may contain positive values canceled by later negative values.

Constraints

  • 0 <= nums.length <= 100000; -1000000000 <= nums[i] <= 1000000000; -100000000000000 <= target <= 100000000000000.
  • All prefix sums and results fit a safe JSON integer. Do not mutate input.

Examples

Example 1

{
  "nums": [
    5,
    -4,
    3
  ],
  "target": 4
}

Returns

3

Example 2

{
  "nums": [
    2,
    3
  ],
  "target": 1
}

Returns

0

Required complexity

O(n log(n + 1)) time and O(n) auxiliary space

What this task practices

Find the Longest Range Within Budget is a coding (algo) interview exercise that trains prompt interpretation, explicit assumptions, a concrete response, and a clear explanation of tradeoffs. The catalog marks it as hard difficulty. It focuses on Technical Reasoning, Testing, Validation. The signed-in workspace provides the tools for the round and evaluates the attempt against task-specific criteria. Reference solutions, hidden checks, evaluator instructions, and candidate work remain private.

Sign in to startThe workspace and evaluation open after sign in.