Ctrl K

Best Repeat-Free Window

Medium
You are given an array of positive integers values and an integer width. Consider every contiguous stretch of the array of length exactly width in which **all numbers are different**. Return the largest sum among those stretches. If no stretch qualifies, return 0. Aim for a single pass over the array.
Example 1
values=[3, 7, 2, 7, 5, 1], width=3 → 14

Windows of length 3: [3, 7, 2] sums to 12, [7, 2, 7] has a repeat, [2, 7, 5] sums to 14, [7, 5, 1] sums to 13. The best is 14.

Example 2
values=[6, 6, 6, 6], width=2 → 0

Every window holds two 6s, so no window qualifies and the answer is 0.

Example 3
values=[4, 9, 1], width=1 → 9
Constraints
  • 1 ≤ width ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo-Genre Stretch of a Playlist MediumWindows With an Exact Alarm Count MediumStretches With k Odd Numbers MediumTwo Separate Segments With a Given Sum MediumTrim the Ends to a Target Medium
loading Python…
Input
values=[3, 7, 2, 7, 5, 1], width=3
Expected
14

Run checks the first 3 tests in your browser. Submit checks all 102 tests on the server, hidden ones included.