Maximum Good Subarray Sum
Real-world version: Best Matched Block of Ledger EntriesThe statement here is our own: the same inputs, outputs and technique.
A ledger holds the signed amounts of a day's entries in the list entries; a credit is positive and a debit is negative.
An auditor works on matched blocks. A matched block is a run of consecutive entries in which the amount of the first entry and the amount of the last entry differ by exactly gap, in either direction. Because gap is at least 1, a matched block always holds at least two entries.
Return the largest total a matched block can have. Return 0 when the ledger has no matched block at all; note that a matched block whose entries happen to total exactly 0 produces the same return value, so the two situations cannot be told apart from the answer alone.
Examples
Example 1
- Input
- entries = [3, 9, 3, 9], gap = 6
- Output
- 24
The whole ledger is a matched block: it starts at 3, ends at 9, and those differ by 6. Its total is 24.
Example 2
- Input
- entries = [4, -100, 6, -100, 4], gap = 2
- Output
- -90
Entries 1 to 3 form a matched block, running 4, -100, 6, since 4 and 6 differ by 2, and it totals -90. Entries 3 to 5 also form one and also total -90.
Example 3
- Input
- entries = [7, 3], gap = 5
- Output
- 0
The only run of two or more entries starts at 7 and ends at 3, which differ by 4 rather than 5, so there is no matched block and the answer is 0.
Constraints
- 2 <= entries.length <= 10^5
- -10^9 <= entries[i] <= 10^9
- 1 <= gap <= 10^9
- Every block total the ledger can produce is between -10^14 and 10^14.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def best_matched_block(entries: list[int], gap: int) -> int:public long bestMatchedBlock(int[] entries, int gap)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 12 test cases: 12 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Check if All the Integers in a Range Are CoveredReal-world version: Patrol Coverage AuditEasy
- Subarray Sum Equals KReal-world version: Trail Elevation StretchesMedium
- Contiguous ArrayReal-world version: Balanced Shift StretchMedium
- Count Number of Nice SubarraysReal-world version: Runs With K Odd ReadingsMedium