KatInterview

Richest Window of Stalls Under Count and Distance Limits

Arrays & HashingAuto-graded · 20 test cases
MediumAuto-gradedArrays & Hashingsliding-windowtwo-pointerssorting

Last updated

Find the best sum over a contiguous run of position-sorted items, limited by item count and coordinate span, using sorting and a two-pointer sweep.

Richest Window of Stalls Under Count and Distance Limits

A market has several stalls laid out along a line. Each stall is described by a pair [position, coins]: where it stands and how many coins it holds. The list is not necessarily sorted, and several stalls may share a position.

You may take coins from a run of stalls. To define a run, first sort all stalls by position in non-decreasing order. A run is any group of stalls that sits next to each other in that sorted order, meaning a contiguous block of the sorted list. A run is allowed if both conditions hold:

  1. It contains at most k stalls.
  2. The position of its last stall minus the position of its first stall is at most d.

Return the largest total number of coins you can collect from a single allowed run.

Notes

  • A run with a single stall is always allowed.
  • Stalls with equal positions may appear in any relative order after sorting. This does not change the answer.
  • Do not modify the input list.

Function Signature

def richest_window(stalls: List[List[int]], k: int, d: int) -> int:

Constraints

  • 1 <= len(stalls) <= 10^5
  • 0 <= position <= 10^9
  • 0 <= coins <= 10^4
  • 1 <= k <= len(stalls)
  • 0 <= d <= 10^9

Examples

Example 1

Input: richest_window([[1, 10], [2, 20], [5, 30], [6, 40]], 2, 2)

Output: 70

Example 2

Input: richest_window([[1, 5], [10, 5], [20, 5]], 2, 5)

Output: 5

Hints

Hint 1

After sorting by position, every allowed selection is a contiguous subarray, so think in terms of windows.

Hint 2

Coins are never negative, so for a fixed right end, the longest allowed window is never worse than a shorter one.

Hint 3

Use two pointers: add the right stall, then advance the left pointer while the window has more than k stalls or spans more than d. Keep a running sum and track the maximum.