Museum Exchange Ledger
Minimum signed difference between two ordered selections
A museum's exchange ledger contains signed transaction amounts in chronological order. Positive amounts represent payments, and negative amounts represent credits.
The curator must choose a divider and form two audit batches:
- Choose exactly
kentries strictly before the divider for the first batch. - Choose exactly
kentries at or after the divider for the second batch. - Entries do not have to be consecutive, and unchosen entries are ignored.
A divider s places indices 0 through s - 1 on its left and indices s through n - 1 on its right, where n is the length of amounts. It must satisfy k <= s <= n - k.
The audit difference is the sum of the first batch minus the sum of the second batch. This is a signed difference, not an absolute difference.
Return [minimum_difference, divider], where minimum_difference is the smallest achievable audit difference across all valid choices. If several dividers achieve that difference, return the smallest divider. You do not need to return the selected entries.
All indices are zero-based.
Examples
Example 1
Input: amounts = [8,1,6,9,2,7], k = 2 Output: [-9,3]
With divider 3, the first batch can use amounts 1 and 6, while the second batch uses 9 and 7. Comparing the best choices at every valid divider shows that this divider gives the smallest signed difference.
Example 2
Input: amounts = [4,4,4,4,4,4], k = 2 Output: [0,2]
Every batch of two entries has the same sum. All valid dividers therefore tie, so the smallest valid divider is returned.
Example 3
Input: amounts = [-5,-2,-8,-1], k = 2 Output: [2,2]
Negative amounts are ordinary signed values. At divider 2, both entries on each side must be selected; the difference is computed by subtracting the second signed sum from the first.
Constraints
- 2 <= amounts.length <= 100000
- -1000000000 <= amounts[i] <= 1000000000
- 1 <= k <= floor(amounts.length / 2)
- The result and all intermediate sums fit in a signed 64-bit integer and are exact JavaScript integers
An O(n log(k + 1)) time solution with O(n + k) auxiliary space is expected. JavaScript Number can represent every sum permitted by the constraints exactly.
Hints
Show hint 1Hint 1
Fix a divider first. Which k entries should be chosen independently on each side?
Show hint 2Hint 2
Maintain the k smallest values while scanning from the left and the k largest values while scanning from the right. Combine their sums at each valid divider.
Follow-up questions
What an interviewer might ask once you have a working solution.
- How would you also return the lexicographically smallest selected index lists for the chosen divider?
- How would the solution change if the two batches required different numbers of entries?
Practice this with an AI interviewer
Explain your approach out loud, write Python or JavaScript, run it against hidden tests (including large inputs), and get a scored debrief.
Start this problem