Bound Found
Time limit1sMemory limit128 MB
For multiple targets, find the contiguous subarray whose absolute sum is closest to the target, reporting that absolute sum.
- Level
Medium6 of 10
- Topics
- Prefix sum, Sorting, Binary search, Two pointers
- Solved
- No attempts yet
Problem
Signals believed to be of extra-terrestrial origin have been received and converted into integer data. Each signal comes in two parts: a sequence of integers and a non-negative integer target .
You are given a sequence of integers and a non-negative target . For every non-empty contiguous subrange (), define its absolute sum as .
Among all subranges, find the one whose absolute sum is closest to — that is, the one minimizing — and output that absolute sum. If two distinct absolute sums are equally close to , output the smaller one.
Input
The input consists of several test cases. Each test case starts with two integers and . The input is terminated by a case with . Otherwise , followed by the integers that make up the sequence, each with absolute value at most . Then follow queries for this sequence; each query is a single target with .
Output
For each query, output on its own line the absolute sum of the subrange whose absolute sum is closest to : the value for a non-empty subrange that minimizes . If two absolute sums are equally close, output the smaller one.